2

I have a FORTRAN program, where I assign PI=3.14159265

when I run the program, my numbers could out slightly off. So i recompiled with debug flags set, and started stepping through with gdb. A few lines in, I notice PI is not what i set it to?

(gdb) s

57 PI=3.14159265

(gdb) s

58 TWOPI= 2* PI

(gdb) print pi

$1 = 3.1415927410125732

What is going on here? I would understand if PI was a system value, but if it is, why is the value wrong?? how should i fix this?

2

3 Answers 3

1

It is printing the best binary approximation to the value of pi you entered; I get exactly the same answer in C using a float. You can get more accuracy by going to double precision, but this is as close as you can get to your value using binary with 32 bits and the usual representation of floating point numbers.

Sign up to request clarification or add additional context in comments.

Comments

1

I'm not a fortan expert by any means, though F77 was the last version that I used. That does look about correct for the estimation which is single precision floating point representation. The short answer is that all numbers are represented in base 2. Single precision floating point representation for 3.14159265 ends up being 3.14159274... The wikipedia article for Single-Precision is surprisingly good for the subject. If you are interested, you should read Goldberg's "What Every Computer Scientist Should Know About Floating-Point Arithmetic".

Your example is actually represented as something pretty close to:

(1 + (4788187 * (2 ^ -23))) * 2

1 Comment

I agree with your suggestions for further reading, in particular placing Goldberg's paper second on the list rather than first.
0

The reason is the rounding done for the representation as floating-point number.

You can define pi as parameter using

REAL, PARAMETER :: pi = 4. * ATAN(1.)  ! set pi = 3.14...

to get a good representation of pi without worrying about the decimal to type in. This approach allows to increase the precession by changing the kind values of pi, 4. and 1.. It might help to get expected results from trigonometric functions, e.g. SIN(pi).

4 Comments

I have been told that pi=acos(-1.0) is 2 bits more accurate than using atan.
@KyleKanos I could not prove this using gfortran 4.8.2.
I was told this by a CS friend of mine, I have yet to test it myself.
In single precision 3.14159250 < pi < 3.14159274 (13176794.6/2^22), the larger value seems obviously closer. ie what joh keyed in is as good as any other approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.