I have executed the below sample program in Scala with different parameters.
object TestScalaWS {
println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet
3+5 //> res0: Int(8) = 8
1.0E5 //> res1: Double(100000.0) = 100000.0
def abs(x: Double) = if (x<0) - x else x //> abs: (x: Double)Double
def sqrtIter(guess: Double, x: Double):Double =
if (isGoodEnough(guess,x)) guess
else sqrtIter(improve(guess,x),x) //> sqrtIter: (guess: Double, x: Double)Double
def isGoodEnough(guess: Double, x: Double) =
abs(guess*guess-x) < 0.001 //> isGoodEnough: (guess: Double, x: Double)Boolean
def improve(guess: Double, x:Double) =
(guess + x/guess)/2 //> improve: (guess: Double, x: Double)Double
def sqrt(x:Double) = sqrtIter(1.0,x) //> sqrt: (x: Double)Double
sqrt(2) //> res2: Double = 1.4142156862745097
sqrt(4) //> res3: Double = 2.0000000929222947
sqrt(0.001) //> res4: Double = 0.04124542607499115
sqrt(0.1e-20) //> res5: Double = 0.03125
sqrt(0.1e20) //> res6: Double = 3.1622776601683793E9
sqrt(1.0e20) //> res7: Double = 1.0E10
sqrt(1E9) //> res8: Double = 31622.776601684047
sqrt(1000000000) //> res9: Double = 31622.776601684047
sqrt(1E10) //> res10: Double = 100000.0
}
But sqrt(10000000000) which is equivalent to 1E10 giving error as "integer number too large" in Scala IDE even I have declared x as Double.
I assume there is some compiler interpret issue but don't know what exactly it means. Is this problem only in Scala ? or exist in Java too. ? or problem with Scala IDE?
Thanks, Gopal.
When you type 10000000000
, you try to define an Int
, same as when you type 1
or -35
.
When you type sqrt(2)
, your Int
is implicitly converted to a Double
, since this is what your function expects, and such an implicit converter does exist.
However, when you type sqrt(10000000000)
, it throws an exception at the first step: defining the integer 10000000000
which is a number larger than Ìnteger.MaxValue`.
What's important to understand is that the conversion to the type you want is done after:
first defining a type for your input (here a number without dot or exponent is considered an Int
)
then parsing the input with the selected type rules (this is the step that throws in your case, because your number cannot be parsed as an Int
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.