Search code examples
printfjuliaprecisionpi

Julia prints wrong Pi digits with @printf


When I compare the output of @printf("%.50f", pi) with BigFloat(pi) the results are different from 16th places. This might be due to type inversion. But I like to go deeper to understands better what is happening here?


Julia> @printf("%.50f", pi)

   3.14159265358979311599796346854418516159057617187500

julia> BigFloat(pi)

3.1415926535897932384626433832795028841971693993751058209749445923078164062861

Solution

  • pi, along with several other well-known irrational numbers, have their own special type Irrational. These are stored to Float64 precision, and I don't think there are any plans to change this going into v1.0.

    If you want higher precision than that, use BigFloat(pi), as you have done in the question.

    But the key point here is that @printf("%.50f", pi) does not automatically wrap a call to BigFloat(pi). To get that behaviour you would need @printf("%.50f", BigFloat(pi)). What you are actually running up against here has nothing to do with pi per se, but rather the manner in which floating point numbers are printed in Julia (in fact, in most programming languages). To see what I mean, try:

    @printf("%.50f", rand())
    

    which is essentially asking Julia to print a random Float64 from the [0,1] interval to 50 decimal places, which is obviously a nonsense request past about 16 decimal places. So why do you get a whole lot of random numbers after the 16th place?

    Quickly and accurately printing Float64 in a nice human-readable format is a topic in its own right. If you are really interested in what is happening, then this article should get you started, but the simple answer is don't pay attention to anything after the usual floating point precision.

    Also, AFAIK, this kind of behaviour is common to most programming languages. This is not Julia-specific behaviour you are observing, but rather behaviour at the processor level.