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 double value 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 pi constant would†.
One caveat, hinted by S. Lott, is that the GCC implementation must hold M_PI in a double data type, and not long double, to ensure equivalence. Both Java and GCC appear to use IEEE-754's 64-bit decimal representation for their respective double data types. The bytewise representation (MSB to LSB) of the library value, expressed as a double, can be obtained as follows (thanks to JeeBee):
pi_bytes.c:
#include
#include
int main()
{
double pi = M_PI;
printf("%016llx\n", *((uint64_t*)&pi));
}
pi_bytes.java:
class pi_bytes
{
public static void main(String[] a)
{
System.out.printf("%016x\n", Double.doubleToRawLongBits( Math.PI ) );
}
}
Running both:
$ gcc -lm -o pi_bytes pi_bytes.c && ./pi_bytes
400921fb54442d18
$ javac pi_bytes.java && java pi_bytes
400921fb54442d18
The underlying representations of M_PI (as a double) and Math.PI are 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.