Subhankar Ghosh
Subhankar Ghosh

Reputation: 469

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!

Upvotes: 4

Views: 295

Answers (2)

phipsgabler
phipsgabler

Reputation: 20980

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.

Upvotes: 7

Steven Siew
Steven Siew

Reputation: 871

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

Upvotes: 4

Related Questions