views:

49

answers:

3

I have a method that returns a float like 1.234567890.I want to test that it really does so. However, it seems that this returned float has different precision on different platforms so how do I assert that the returned value is 1.23456789? If I just do:

$this->assertEqual(1.23456789, $float);

Then that might fail on some platforms where there is not enough precision.

+2  A: 

For greater accuracy you may consider using BCMath.

Sarfraz
bccomp() suits my situation fine.
rFactor
A: 

Alternatively of using bcmath() you can also set the default precision, like this:

ini_set('precision', 14);
Alix Axel
+1  A: 

In general, it's a bad idea to test built-in floats for equality. Because of accuracy problems of floating point representation, the results of two different calculations may be perfectly equal mathematically, but different when you compare them at your PHP runtime.

Solution 1: compare how far apart they are. Say, if the absolute difference is less than 0.000001, you treat the values as equal.

Solution 2: use arbitrary precision mathematics, which supports numbers of any size and precision, represented as strings.

Ivan Krechetov
+1 for never testing floats for equality. Scary how many people are not aware of this. Wish I could upvote more...
sleske
Right, sleske. I learned it for real long time ago writing my own ray tracing program, and wondering why I only get several dots on the screen instead of beautifully lit polygons. :-)
Ivan Krechetov