Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arbitrary precision floating types in Julia

I have a constant value:

M_LN2 = 0.693147180559945309417

I tried storing it as:

M_LN2 = BigFloat(0.693147180559945309417)

The result seems to be adding too many extra digits:

6.931471805599452862267639829951804131269454956054687500000000000000000000000000e-01

I tried:

M_LN2 = Float64(0.693147180559945309417)

But it is truncating the value:

0.6931471805599453

Could you suggest what would be the correct way to initialize the constant? Thanks!

like image 256
Subhankar Ghosh Avatar asked Dec 17 '22 21:12

Subhankar Ghosh


2 Answers

When you write BigFloat(0.693147180559945309417), Julia constructs a Float64 value of the literal value 0.69314718055994530941, which already performs some truncation:

julia> 0.69314718055994530941
0.6931471805599453

The resulting value is then passed as an argument to the BigFloat function. To avoid that, you have to circumvent the parsing of the numeric literal. The most convenient way for that is the big string macro:

julia> big"0.693147180559945309417"
6.931471805599453094169999999999999999999999999999999999999999999999999999999979e-01

Which internally probably does just parse(BigFloat, "0.693147180559945309417") to "manually" parse the value from the given string, without interpretation from Julia in between.

like image 81
phipsgabler Avatar answered Dec 28 '22 16:12

phipsgabler


The secret is to enclose your number with quotes ("). So the value is converted directly from String into BigFloat.

julia> println("Julia version ",VERSION); 
       M_LN2 = BigFloat("0.693147180559945309417")
Julia version 1.0.0
6.931471805599453094169999999999999999999999999999999999999999999999999999999979e-01
like image 36
Steven Siew Avatar answered Dec 28 '22 16:12

Steven Siew