I am coding several reference algorithms in both Java and C/C++. Some of these algorithms use π. I would like for the two implementations of each algorithm to produce identical results, without rounding differently. One way to do this that has worked consistently so far is to use a custom-defined pi constant which is exactly the same in both languages, such as 3.14159. However, it strikes me as silly to define pi when there are already high-precision constants defined in both the Java and GCC libraries.
I’ve spent some time writing quick test programs, looking at documentation for each library, and reading up on floating-point types. But I haven’t been able to convince myself that java.lang.Math.PI (or java.lang.StrictMath.PI) is, or is not, equal to M_PI in math.h.
GCC 3.4.4 (cygwin) math.h contains:
#define M_PI 3.14159265358979323846
^^^^^
but this
printf("%.20f", M_PI);
produces
3.14159265358979311600
^^^^^
which suggests that the last 5 digits cannot be trusted.
Meanwhile, Javadocs say that java.lang.Math.PI is:
The
doublevalue that is closer than
any other to pi, the ratio of the
circumference of a circle to its
diameter.
and
public static final double PI 3.141592653589793d
which omits the questionable last five digits from the constant.
System.out.printf("%.20f\n", Math.PI);
produces
3.14159265358979300000
^^^^^
If you have some expertise in floating-point data types, can you convince me that these library constants are exactly equal? Or that they are definitely not equal?
Yes, they are equal, and using them will insure that GCC and Java implementations of the same algorithm are on the same footing – at least as much as using a hand-defined
piconstant would†.One caveat, hinted by S. Lott, is that the GCC implementation must hold
M_PIin adoubledata type, and notlong double, to ensure equivalence. Both Java and GCC appear to use IEEE-754’s 64-bit decimal representation for their respectivedoubledata types. The bytewise representation (MSB to LSB) of the library value, expressed as adouble, can be obtained as follows (thanks to JeeBee):pi_bytes.c:
pi_bytes.java:
Running both:
The underlying representations of
M_PI(as adouble) andMath.PIare identical, down to their bits.† – As noted by Steve Schnepp, the output of math functions such as sin, cos, exp, etc. is not guaranteed to be identical, even if the inputs to those computations are bitwise identical.