Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate Irrational with Julia

Julia has the built-in constant pi, with type Irrational.

julia> pi
π = 3.1415926535897...

julia> π
π = 3.1415926535897...

julia> typeof(pi)
Irrational{:π}

Coming from SymPy, which has the N() function, I would like to evaluate pi (or other Irrationals, such as e, golden, etc.) to n digits.

In [5]: N(pi, n=50)
Out[5]: 3.1415926535897932384626433832795028841971693993751

Is this possible? I am assuming that pi is based on its mathematical definition, rather than just to thirteen decimal places.

like image 974
2Cubed Avatar asked Sep 02 '16 01:09

2Cubed


2 Answers

Sure, you can set the BigFloat precision and use big(π). Note that the precision is binary; it's counted in bits. You should be safe if you set the precision to at least log2(10) + 1 times the number of digits you need.

Example:

julia> setprecision(BigFloat, 2000) do
           @printf "%.200f" big(π)
       end
3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196

Here I've set the precision a little higher than it needs to be for just 200 digits.

The digits are computed in the GNU MPFR library.

like image 141
Fengyang Wang Avatar answered Oct 19 '22 22:10

Fengyang Wang


Julia has an interface for the SymPy package:

# Pkg.add("SymPy")  ## initial installation of package
using SymPy
julia> N(PI, 50)
3.14159265358979323846264338327950288419716939937508

Note that SymPy uses the uppercase PI to distinguish it's object from the lowercase pi in native Julia. You'll also need the native SymPy installed on your computer to get full functionality here.

Other comments:

  • see here for a longer tutorial on Julia SymPy with a lot of good examples.
like image 21
Michael Ohlrogge Avatar answered Oct 19 '22 23:10

Michael Ohlrogge