What actually happens is the computer only has 64 bits to work with. It has to throw away the low order part of any result after every operation. On every calculation you accumulate a little more roundoff error. In the newer Java’s the computer is permitted to secretly retain a few extra bits of accuracy during a short string of calculation, so sometimes they come out more accurate that you would theoretically expect. (They almost never come out more accurate than a newbie expects.) To discourage use of these guard bits and get reproducibly less accurate results you use the StrictMath library. Unless you really know what you are doing, you must presume the results are never precisely bang on. Don’t count on results that in theory should be integers coming out precisely as integers. Never compare == or !=, check within a tolerance. Keep in mind when you compare > >= < <= the values you are comparing may, as a side effect of calculation, have drifted just above or just below your test limits. Sometimes you may want to include some slop/tolerance in your limits. Java is somewhat better than other languages since it specifies strict IEEE rules. Fortunately, in Java, if a number has a perfect integer floating point representation and you divide it by another such number that is a factor, the result is guaranteed to be a perfect integer representation.
The other source of the fuzz is accumulating roundoff error from cascaded operations. Further, there are errors in trig functions not being bang on 0 or 1 as you expect. This is a result of accumulated roundoff error in evaluating polynomials and in the polynomial approximations themselves used internally to compute the trig functions.
For example, Math.E = 2.718281828459045 but Math. exp( 1.0 ) = 2.7182818284590455
if ( f == 100.00 )say
if ( f > 99.995 )
if ( Math.abs( value - target ) < epsilon )or
if ( value >= target - epsilon && value <= target + epsilon )
when the order of magnitude of target is unknown, you might use some slower code like this, presuming
if ( Math.abs( value - target ) < epsilon * target )or
if ( value >= target * ( 1 - epsilon ) && value <= target * ( 1+ epsilon ) )
Use a mixture of ints and float /doubles. Use the ints for your loop counting.
Instead of incrementing a floating point variable, recreate it from an int loop variable, e. g. instead of:
f += 0.001;code
f = i * 0.001;
To study the IEEE format, you can use Double.doubleToLongBits and Double.longBitsToDouble.
String Double.toString( double )Java wants to preserve every drop of precision it has, so that if you convert it back with:
double Double.parseDouble( String )you will get back to the precise same binary representation. This is all very well, but from the point of view of humans, the display looks wrong, as if result were slightly inexact and with way too many digits. This also makes the rounding error distressingly visible. To fix it and create something that looks pleasingly rounded to humans, use java.text.DecimalFormat to limit the number of digits displayed to what you actually want/need.
If you are merely trying to round for internal purposes use Math.round, Math.floor, Math.ceil and Math.rint. Math.round gives a long result, the rest double. You can create variants by adding .5 and multiplying and dividing by powers of ten. There is generally no need to convert to int or long and back.
Comparison of Pentium Floating Point and Integer Speeds | ||
---|---|---|
Operation | Floating Point clocks | Integer Clocks |
add | 1-3 | 1-3 |
multiply | 1-3 | 10-11 |
division | 39-42 | 22-46 |
convert | 6 (double to long) | 3 (long to double) |
Double precision arithmetic has very little speed penalty on modern CPUs (Central Processing Units). Normally you should use double in preference to float. It gives you 14 to 15 significant digits where float gives only 6 to 7. The only advantage to float is compactness. In comparison, a typical scientific pocket calculator will give you 10 significant digits and will automatically round for display. When do you use float and when double? It depends how much precision you need. Because modern floating point hardware is all built on double, normally the only time you use float is for float[] or for float fields in plentiful Objects to conserve space when you don’t need the precision.
Other odd results you can get from floating point operations include Double. NEGATIVE_INFINITY, Double. POSITIVE_INFINITY and positive and negative 0. There is a similar method for checking for infinity, Double. isInfinite.
0./0. gives NaN, 1./0. gives POSITIVE_INFINITY and -1./0. gives NEGATIVE_INFINITY.
Because there are two different flavours of NAN, Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY You can’t directly compare == Double.NAN to check for NAN. However, you can Double.isNaN or directly compare == Double.NAN; However, you can use == to compare with Double.POSITIVE_INFINITY. There is a corresponding Float. NaN and Float.isNaN The theory is making NaN not equal to itself allows a quick and dirty way to test for a calculation going haywire.
if ( result != result ) { out.println( "oops" ); }
// fast accurate way to cube a number double y = x * x * x;rather
// slow, inaccurate way to cube a number double y = Math.pow( x, 3 );Ditto for squaring. Further, if x is an integer, you will get a precise result using only simple arithmetic. If you use: Math. pow you will lose precision. Also use
// fast way to do a square root double y = Math.sqrt( x );in
// slow way to do a square root double y = Math.pow( x, 0.5 );
Common Floating Point Calculation | |
---|---|
Method | Purpose |
+ | addition. |
- | subtraction. |
* | mulitplication. |
/ | division, with a fractional result. If you divide by 0/0, 7/0 or overflow the maximum representable number, you won’t get an exception. You will get a special marker result. You can test for it with Math. isInfinite or isNaN. |
Oracle’s Javadoc on Math.abs : available:
|
absolute value. |
Oracle’s Javadoc on Math.cbrt : available:
|
cube root. |
Oracle’s Javadoc on Math.ceil : available:
|
ceiling, next highest integer. |
Oracle’s Javadoc on Math.exp : available:
|
ex. |
// compute exponent if number were written in scientific notatation int exponent = (int) (Math.floor( Math.log10( value ))) + 1; // e.g. 12345.0 -> 0.12345E06 -> exponent 6, mantissa 0.123454. // Regular (int) rounds toward 0. |
base 10 exponent were the number written in scrientific notation. Internally number use IEEE binary exponents. Can also be used to determine the number of places to the left or right of the decimal point. |
Oracle’s Javadoc on Math.hypot : available:
|
hypotenuse, distance from origin to a point: sqrt( x² + y² ). Note if you want to do is compare two distances, you don’t need the sqrt. |
Oracle’s Javadoc on Math.log : available:
|
natural log, base e log, ln. Not base 10 common logarithm! Math.log gives: 0.01 ⇒ -4.6051, 0.1 ⇒ -2.3026, 1.0 ⇒ 0.0, 10.0 ⇒ 2.3026, 100.0 ⇒ 4.6052. |
Oracle’s Javadoc on Math.log10 : available:
|
base 10 log. Math.log10 gives: 0.01 ⇒ -2.0, 0.1 ⇒ -1.0, 1.0 ⇒ 0.0, 10.0 ⇒ 1.0, 32.0 ⇒ 1.50514, 50.0 ⇒ 1.69897, 100.0 ⇒ 2.0. |
// compute mantissa if number were written in scientific notatation int exponent = (int)(math.floor( Math.log10( value ))) + 1; double mantissa = value * Math.pow( 10.0, -exponent ); // e.g. 12345.0 -> 0.12345E06 -> exponent 6, mantissa 0.123454. // regular (int) rounds toward 0. |
base 10 mantissa were the number written in scientific notation. Internally Java uses IEEE binary exponents. |
Oracle’s Javadoc on Math.max : available:
|
larger of two numbers. |
Oracle’s Javadoc on Math.min : available:
|
smaller of two numbers. |
Oracle’s Javadoc on Math.pow : available:
|
power, ab. |
Oracle’s Javadoc on Math.rint : available:
|
round to nearest integer. Result is a double that is an integer. |
Oracle’s Javadoc on Math.round : available:
|
round to nearest integer. Result is an long. |
Oracle’s Javadoc on Math.signum : available:
|
Returns the signum function of the argument; 0 if == 0, 1.0 if > 0, -1.0 if < 0. The result is a double, not an int as you would expect. |
Oracle’s Javadoc on Math.sqrt : available:
|
square root. |
This page is posted |
http://mindprod.com/jgloss/floatingpoint.html | |
Optional Replicator mirror
|
J:\mindprod\jgloss\floatingpoint.html | |
Please read the feedback from other visitors,
or send your own feedback about the site. Contact Roedy. Please feel free to link to this page without explicit permission. | ||
Canadian
Mind
Products
IP:[65.110.21.43] Your face IP:[3.236.112.101] |
| |
Feedback |
You are visitor number | |