julia c^3 results in wrong, negative number

Viewed 62

So I was using light speed c to do some calculations in VScode and I found this:

julia> c = 3*10^8
300000000

julia> c^3
-1238598680542445568

It's obviously wrong. But if I define c as float number:

julia> c = 3.0*10^8
3.0e8

julia> c^3
2.7e25

Then everything is fine. What is happening? Is this some inherent error within julia or I am asking some silly question?

2 Answers

Use BigInts for that as integers in Julia are normally 64 bits:

julia> c = big(3*10^8)
300000000

julia> typeof(c)
BigInt

julia> c^3
27000000000000000000000000

This is the overflow behavior of int type

julia> x = typemax(Int64)
9223372036854775807

julia> x + 1
-9223372036854775808

julia> x + 1 == typemin(Int64)
true

While floating point numbers are not exact values, and they handle the mantissa and exponent separately hence they are able to return correct answers even for large order calulations.

Related