ClustrMaps

The roadrunner is back as never before! See also: My homepage or my very obsolete site
If by any means entries in my blog are considered to be harmful or damaging, please let me know (add comment) or just mail me. In this (unhopely) case I will remove or change the contents.

Sunday, January 28, 2007

Java and the persistant arrogancy of Sun.
See this simple Java source:


import java.math.BigDecimal;

public class TestDouble {

/**
* Translates a double into a BigDecimal. The scale
* of the BigDecimal is the smallest value such that
* (10scale * val) is an integer.
*


* Note: the results of this constructor can be somewhat unpredictable.
* One might assume that new BigDecimal(.1) is exactly equal
* to .1, but it is actually equal
* to .1000000000000000055511151231257827021181583404541015625.
* This is so because .1 cannot be represented exactly as a double
* (or, for that matter, as a binary fraction of any finite length).
* Thus, the long value that is being passed in to the constructor
* is not exactly equal to .1, appearances notwithstanding.
*


* The (String) constructor, on the other hand, is perfectly predictable:
* new BigDecimal(".1") is exactly equal to .1, as one
* would expect. Therefore, it is generally recommended that the (String)
* constructor be used in preference to this one.
*
* @param val double value to be converted to BigDecimal.
* @throws NumberFormatException val if val is
* infinite or NaN.
*/
public static void main(String[] args) throws Exception {
double d = 0.1;
System.out.println(d);
System.out.println(new BigDecimal(d));
System.exit(0);
}

}

And it's output when run:
0.1
0.1000000000000000055511151231257827021181583404541015625

This is far from expected.

See also: http://www.javaranch.com/newsletter/July2003/MoneyInJava.html

Or this Sun form entry: http://forum.java.sun.com/thread.jspa?forumID=256&threadID=252852

No comments: