After running the following lines :
double d=Float.parseFloat("9.99");
System.out.println(""+d);
I got this : 9.989999771118164
I expected to see : 9.99
Why and how to fix this ?
=======================================================
Edit : What I should have used was : double d=Double.parseDouble("9.99") which prints out 9.99. That's my fault, but it's interesting to see the detailed answers, thanks !
If you want exact decimal values, use BigDecimal. Otherwise, learn how binary floating point works, and be prepared to deal with the consequences. (Even BigDecimal won't be able to represent something like "a third" exactly, of course.)
Note that it's quite odd to call Float.parseFloat, but assign the result to a double... it would be more usual to either assign the result to a float or to use Double.parseDouble to start with. In either case, however, the result will not be exactly 9.99. The number 9.99 can't be represented exactly in binary floating point any more than the result of dividing one by three can be written exactly in a decimal representation.
I don't have any articles about Java binary floating point in particular, but there shouldn't be any really significant differences between that and C# binary floating point, which I do have an article about.
Which type you should use really depends on the semantics of what you're representing. I use a rule of thumb that manmade "artificial" values such as money are best represented in decimal formats (e.g. BigDecimal) whereas "natural" values such as height and width are more appropriate as float/double.
The number 9.99 cannot be represented exactly as a floating point number, so Float.parseFloat returned the closest representable floating point number.
For more information, search "what every computer scientist should know about floating-point arithmetic" on google.
This has nothing to do with Java. It's related to floating point representation. If you want to represent the number as a two decimal floating point, I suggest you to use printf or String.format:
System.out.println(String.format("%.2f", 9.99));
Regards
Floating point numbers are still represented by bits, which have a limited number of possible configurations, so even floating point numbers are discrete (they cannot represent values with arbitrary precision and rounding occurs). What you're observing here is a floating point inaccuracy, 9.99 cannot be exactly represented by the data type. How you "fix" this depends on what you want to do with.
If you try Double.parseDouble() instead you will the expected result.
Related
I understand that due to the nature of a float/double one should not use them for precision important calculations. However, i'm a little confused on their limitations due to mixed answers on similar questions, whether or not floats and doubles will always be inaccurate regardless of significant digits or are only inaccurate up to the 16th digit.
I've ran a few examples in Java,
System.out.println(Double.parseDouble("999999.9999999999");
// this outputs correctly w/ 16 digits
System.out.println(Double.parseDouble("9.99999999999999");
// This also outputs correctly w/ 15 digits
System.out.println(Double.parseDouble("9.999999999999999");
// But this doesn't output correctly w/ 16 digits. Outputs 9.999999999999998
I can't find the link to another answer that stated that values like 1.98 and 2.02 would round down to 2.0 and therefore create inaccuracies but testing shows that the values are printed correctly. So my first question is whether or not floating/double values will always be inaccurate or is there a lower limit where you can be assured of precision.
My second question is in regards to using BigDecimal. I know that I should be using BigDecimal for precision important calculations. Therefore I should be using BigDecimal's methods for arithmetic and comparing. However, BigDecimal also includes a doubleValue() method which will convert the BigDecimal to a double. Would it be safe for me to do a comparison between double values that I know for sure have less than 16 digits? There will be no arithmetic done on them at all so the inherent values should not have changed.
For example, is it safe for me to do the following?
BigDecimal myDecimal = new BigDecimal("123.456");
BigDecimal myDecimal2 = new BigDecimal("234.567");
if (myDecimal.doubleValue() < myDecimal2.doubleValue()) System.out.println("myDecimal is smaller than myDecimal2");
Edit: After reading some of the responses to my own answer i've realized my understanding was incorrect and have deleted it. Here are some snippets from it that might help in the future.
"A double cannot hold 0.1 precisely. The closest representable value to 0.1 is 0.1000000000000000055511151231257827021181583404541015625. Java Double.toString only prints enough digits to uniquely identify the double, not the exact value." - Patricia Shanahan
Sources:
https://stackoverflow.com/a/5749978 - States that a double can hold up to 15 digits
I suggest you read this page:
https://en.wikipedia.org/wiki/Double-precision_floating-point_format
Once you've read and understood it, and perhaps converted several examples to their binary representations in the 64 bit floating point format, then you'll have a much better idea of what significant digits a Double can hold.
As a side note, (perhaps trivial) a nice and reliable way to store a known precision of value is to simply multiply it by the relevant factor and store as some integral type, which are completely precise.
For example:
double costInPounds = <something>; //e.g. 3.587
int costInPence = (int)(costInPounds * 100 + 0.5); //359
Plainly some precision can be lost, but if a required/desired precision is known, this can save a lot of bother with floating point values, and once this has been done, no precision can be lost by further manipulations.
The + 0.5 is to ensure that rounding works as expected. (int) takes the 'floor' of the provided double value, so adding 0.5 makes it round up and down as expected.
Why this java code returns 61.004999999999995 instead of 61,005 ?? I donĀ“t get it.
System.out.println(105*0.581);
It occurs due to the nature of floating point numbers . Computers are not very intelligent working with floating point numbers , so we have to work based on approximations.
Instead of 6.005 == 6.004999 , you should do this: 6.005 - 6.004999 < = 0.001
You fall into a floating point precision problem. In computer science there is a simple (but anoing) fact : you cannot represent all real numbers. It's also true for Java.
If you want to go deeper, you can study how floating point number are stores in memory. Key words are : bit of sign; mantissa and exponent. Be aware that the precision also depends on the system memory (32or64)
http://en.wikipedia.org/wiki/Single-precision_floating-point_format
Java speaking, for more precision you can use BigDecimal :
System.out.println(new BigDecimal(105).multiply(new BigDecimal(0.581));
You can also round it with round(MathContext mc) which in this case will give you 61.005 if you set the precision to 5.
System.out.println(new BigDecimal(105).multiply(new BigDecimal(0.581)).round(new MathContext(5)));
https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html
If it's just a question about how to display it and the precision dosen't matter, you can use the DecimalFormat.
System.out.println(new DecimalFormat("###.###").format(105*0.581));
https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html
I have A String that is formatted correctly to be cast to a double and it works fine for most decimals. The issue is that for .33, .67, and possibly others I haven't tested, the decimal becomes something like .6700000000002, or .329999999998. I understand why this happens but does any one have a suggestion to fix it.
It's a result of IEEE-754 rounding rules, some numbers cannot be represented precisely in two's complement. For example, 1/10 is not precisely representable.
You can add more precision (but not infinite) by using BigDecimal.
BigDecimal oneTenth = new BigDecimal("1").divide(new BigDecimal("10"));
System.out.println(oneTenth);
Which outputs 0.1
Some decimal numbers can not be represented accurately with the internal base 2 machine representation.
That's double precision for you. Binary numbers and decimals don't work well together. Unless you are doing something really precise it should be fine, if you are printing it you should use either decimal format or printf.
Value of floating point numbers are not stored directly but with exponential values. You may write 3.1233453456356 as number, but this is stored something like 3 and 2^6 in memory. It tries to store a value as close as your number, but those differences can happen.
It shouldn't be a problem unless you're testing for equality. With floating-point tests for equality you'll need to allow a "delta" so that:
if (a == b)
becomes
if (abs(a-b) < 0.000001)
or a similar small delta value. For printing, limit it to two decimal places and the formatter will round it for you.
I have the following statement:
float diff = tempVal - m_constraint.getMinVal();
tempVal is declared as a float and the getMinVal() returns a float value.
I have the following print out:
diff=0.099999905, tempVal=5.1, m_constraint.getMinVal()=5.0
I expect the diff is 0.1 but not the above number. how to do that?
Floats use the IEEE754 to represent numbers, and that system has some rounding errors.
Floating point guide
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Wikipedia on IEE754
Bottom-line if you are doing arithmetic and it needs to be exact don't use float or double but us BigDecimal
Because of the way they store values internally, floats and doubles can only store completely accurately numbers which can be decomposed into a sum of powers of 2 (and then, within certain constraints relating to their absolute and relative magnitude).
So as soon as you attempt to store, or perform a calculating involving, a number which cannot be stored exactly, you are going to get an error in the final digit.
Usually this isn't a problem provided you use floats and doubles with some precaution:
use a size of floating point primitive which has "spare" digits of precision beyond what you need;
for many applications, this probably means don't use float at all (use double instead): it has very poor precision and, with the exception of division, has no performance benefit on many processors;
when printing FP numbers, only actually print and consider the number of digits of precision that you need, and certainly don't include the final digit (use String.format to help you);
if you need arbitrary number of digits of precision, use BigDecimal instead.
You cannot get exact results with floating point numbers. You might need to use a FixedPoint library for that. See : http://sourceforge.net/projects/jmfp/
Java encodes real numbers using binary floating point representations defined in IEEE 754. Like all finite representations it cannot accurately represent all real numbers because there is far more real numbers than potential representations. Numbers which cannot be represented exactly (like 0.1 in your case) are rounded to the nearest representable number.
If I have a number like 3.01 the computer seems to think the best double is the 64 bit number:
3.0099999999999997868371792719699442386627197265625
Is there some way better than looking for say more than four 9's or 0's that I can generically "round" to the precise base 10 representation?
Is there an algo that would take that 3.00999999... mess and return 3.01 WITHOUT me specifying that I want that precision.
I think most of the numbers I'm dealing with should be small enough that 64-bits will not have ambiguities.
No - because presumably you might have actually specified 3.0099999999999997868 as the input number, and wouldn't want that same value to be rounded to 3.01. Basically, you've lost information when converting from a decimal value to binary floating point - you can't get that information back.
If you're interested in decimal values rather than just the magnitude, you should consider using BigDecimal instead of double. (What do these values represent?)
EDIT: As noted by other answers, Java will give you 3.01 anyway when you just use toString, however you came to the original value. This is specified in Double.toString:
How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x, then d must be one of them and the least significant bit of the significand of d must be 0.
If that's good enough for you, it'll make life easier... but it sounds like you should be thinking about it more fundamentally.
If you want 10 digits of precision, you need to round to that precision. Even if you use BigDecimal you can avoid representation error, but sooner or later you will have to know how to deal with precision.
double d = 3.01;
System.out.println(d); // rounds the answer slightly
prints
3.01
There are many workarounds for representation and rounding error, however often the built in tools will deal with it for you.
It's clear that you cannot expect to always get the original number back since there are many numbers that map to the same float. For example, you cannot distinguish between these numbers:
3.0099999999999997868371792719699442386627197265625
3.009999999999999786837179271969944238662
3.009999999999999786837179271
3.0099999999999997
3.01
However, Python has an interesting take on this: if you give it the number 3.0099999999999997868371792719699442386627197265625, it will reply with 3.01:
Python 2.7.2+ (default, Nov 30 2011, 19:22:03)
[GCC 4.6.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 3.0099999999999997868371792719699442386627197265625
3.01
This is becauuse 3.01 is the shortest string that gives the same floating point number. In other words, it's the shortest x so that
float(repr(x)) == x
where repr is the Python function that turns an object into a string (here it turns 3.0099... into 3.01) and float converts a string to a float.
There are obvisouly many strings that will result in the same internal float, but this is the shortest and therefore "probably" what you meant.
This feature was added in Python 2.7, as a backport of a Python 3.1 feature. It was discussed in Issue1580 and you should be able to find the code there and translate it into Java if you want.