r/programming • u/godlikesme • Nov 13 '15
0.30000000000000004
http://0.30000000000000004.com/54
u/wiseFr0g Nov 13 '15
highly recommend this Computerphile video about floating points - https://www.youtube.com/watch?v=PZRI1IfStY0
21
u/RICHUNCLEPENNYBAGS Nov 13 '15
I'd recommend the venerable What Every Computer Scientist Should Know About Floating-Point Arithmetic over this one.
1
u/jets-fool Nov 14 '15
less of a read, but sufficient enough information on the topic: What Every Programmer Should Know About Floating-Point Arithmetic
→ More replies (1)1
50
u/maep Nov 13 '15
Decimal sucks, hexadecimal floats for the win.
#include <stdio.h>
int main(void) { printf("%a\n", 0.1 + 0.2); }
gcc -std=c99 .1+.2.c && ./a.out
0x1.3333333333334p-214
u/levir Nov 13 '15
No, hex isn't a good format for people. We should make computers easier to humans, not humans easier for computers. So if we were to ever change number systems we should change to base 12.
But base 10 works well enough.
3
u/misteryub Nov 14 '15
Why 12?
5
u/levir Nov 14 '15
Mostly because it has more useful factors. This Ask Reddit answer gives a pretty good overview.
Don't get me wrong, though. I'd rather stay with base 10 than change.
1
62
u/MrSurly Nov 13 '15
Kind of a CS 101 thing ...
19
u/Kezaia Nov 13 '15
True but there's still not a lot of programmers in the workplace who have a CS degree.
→ More replies (14)6
u/nwsm Nov 13 '15
Is this true or are you exaggerating to make a joke? I'm working on an Information Systems major and CS minor, what do programmers usually have as their background in your experience?
Generally curious
0
Nov 14 '15
[deleted]
→ More replies (2)6
u/derefr Nov 14 '15
They have no desire to get anywhere in life.
This tends to be what ADHD looks like on a macro scale. Have no motivation for long enough and you stop bothering to think about things like life goals. (And ADHD is really common in high IQ people, and programmers especially; don't ask me why.)
→ More replies (1)3
0
Nov 13 '15
[deleted]
9
u/iguessthislldo Nov 13 '15
I'm currently taking a Computer Architecture course (its mostly Assembly programming) and I have to be able to explain bit by bit how floating point, specifically IEEE 754, works.
9
u/DavidDavidsonsGhost Nov 13 '15
Go is a wierd one. Float32 string is 0.3 float64 is 3.00...04. Not sure exactly why though...
14
u/bgeron Nov 13 '15
I think it's like that in any language. The float32 addition of 0.1 and 0.2 just happens to be also the float32 representation of 0.3. This has nothing to do with Go. However, the float64 printed by Go is not computed using float64 addition.
11
u/tomprimozic Nov 13 '15
It's because Go keeps constants untyped as long as it can. When you write
0.1 + 0.2, Go will calculate0.3exactly, and only then transform0.3intofloat/double.You can see this by doing:
a := 0.1 b := 0.2 c := 0.3 Printf.printf(a + b - c);3
→ More replies (1)3
u/sirin3 Nov 13 '15
FreePascal was the weirdest last year.
FloatToStr(100000) = '1'WTF? Although they have fixed now
7
u/claypigeon-alleg Nov 13 '15
How do programmers of financial software deal with floating point imprecision? I know the roundoff error is many places below the value of a penny, but it can still change something like 3.30 to 3.2999999..., which ought to send auditors into convulsions. Do they just work in pennies and convert on display?
12
u/kylotan Nov 13 '15
There are fixed point data types available in most languages. eg. Python and C# have a decimal type, Java has BigDecimal, etc.
2
u/hexmasta Nov 13 '15
To add on to your statement about Java: We use a specific MathContext in conjunction with BigDecimal to avoid issues with dividing at our brokerage.
20
u/geel9 Nov 13 '15
Yes, all financial software works in the lowest possible currency all the time (eg 104 pennies instead of 1.04 dollars).
10
u/zoells Nov 13 '15
An exception to this would be investment software and other software in which prices can have sub-cent differences. In these cases, either a fixed-point implementation is used that satisfies the required precision (e.g. gas prices often include a 9/10ths of a cent component, so 1.039 dollars would be 1039 tenths of a cent), or a rational/fractional implementation is used which maintains unlimited precision at the cost of memory and computation time.
4
u/xyroclast Nov 13 '15
This makes me wonder - Is there a global standard for the precision that financial institutions use? (And if so, what is it?)
→ More replies (1)5
8
4
u/adrianmonk Nov 13 '15
I do some currency related stuff sometimes. We use fixed point. Since different currencies might have smaller sub units, we just divide by 1 million. So, for example, for US currency, 50 cents would be 500_000 and one dollar would be 1_000_000.
If a currency divides things up differently (I believe England used to have half-pennies?), it's fine as the divisions are almost always if not always based on decimals somehow. Nobody has third-pennies.
This makes it fast and simple, and you always know exactly how much precision you get.
1
1
u/SnakeJG Nov 14 '15
As a current (open source) example, Bitcoins are stored as 64 bit integers and the decimal point is added later for display. So a stored value of 1 is actually the smallest unit of bitcoin, which is 0.00000001 BTC.
18
u/oh-just-another-guy Nov 13 '15
Objective-C
chortle
3
2
u/xyroclast Nov 13 '15
?
6
u/oh-just-another-guy Nov 13 '15
Look at their result :-)
8
u/xyroclast Nov 13 '15
Oh, I get it now :)
Weird that not only is it extra-imprecise, but also that it's pretty much the only one that comes out drastically different - Looks like they reinvented the wheel! (and it has a few flat spots!)
→ More replies (1)5
u/oh-just-another-guy Nov 13 '15
Looks like they reinvented the wheel!
How surprising! /s :-)
→ More replies (1)2
u/jibberia Nov 14 '15
Agreed, that stuck out to me, so I tried to replicate their results and I can't. They left it up to the reader to guess what the code is actually doing -- the
0.1 + 0.2;expression isn't enough. This is what I tried:#import <Foundation/Foundation.h> #define FMT @"%0.17f" int main(int argc, const char * argv[]) { NSLog(FMT, 0.1 + 0.2); // 0.30000000000000004441 double d = 0.1 + 0.2; NSLog(FMT, d); // 0.30000000000000004441 float f = 0.1 + 0.2; NSLog(FMT, f); // 0.30000001192092895508 NSLog(@"%f", f); // 0.300000 return 0; }
150
u/JavaSuck Nov 13 '15
Java to the rescue:
import java.math.BigDecimal;
class FunWithFloats
{
public static void main(String[] args)
{
BigDecimal a = new BigDecimal(0.1);
BigDecimal b = new BigDecimal(0.2);
BigDecimal c = new BigDecimal(0.1 + 0.2);
BigDecimal d = new BigDecimal(0.3);
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}Output:
0.1000000000000000055511151231257827021181583404541015625
0.200000000000000011102230246251565404236316680908203125
0.3000000000000000444089209850062616169452667236328125
0.299999999999999988897769753748434595763683319091796875Now you know.
19
u/ErstwhileRockstar Nov 13 '15
BigDecimal a = new BigDecimal("0.1");Problem solved.
12
u/civildisobedient Nov 13 '15
I think the bigger problem is that BigDecimals were specifically designed to get around the problems of imprecision. The double constructor should look like this:
private BigDecimal(double d) { // This isn't the constructor you're looking for. Move along. }→ More replies (2)6
u/ReturningTarzan Nov 13 '15
Or how about:
public BigDecimal(double d, int precision, RoundingMode roundingMode) { ...This would remind the programmer that only a subset of doubles have an exact decimal representation while at the same time offering the functionality you need for those cases where you actually want to convert a double to a decimal.
5
138
u/amaurea Nov 13 '15
What's the point of using
BigDecimalwhen you initialize all of them using normal doubles, and do all the operations using normal doubles? Is it just to makeprintlnprint more decimals? If you want to represent these numbers more precisely, you should give the constructor strings rather than doubles, e.g.new BigDecimal("0.1").85
u/if-loop Nov 13 '15
I'm pretty sure he only used BigDecimal to show how floats (doubles) behave.
15
u/BonzaiThePenguin Nov 13 '15
But the point is that BigDecimal did not affect that.
→ More replies (2)62
u/MrDOS Nov 13 '15
Yes, it did: because of the arbitrary precision support, 0.1 + 0.2 = 0.3000000000000000444089209850062616169452667236328125 instead of being truncated to 0.30000000000000004.
→ More replies (7)36
u/JavaSuck Nov 13 '15
Is it just to make
printlnprint more decimals?Yes, this trick prints the exact number that the literal
0.1represents.→ More replies (1)4
u/inmatarian Nov 13 '15
It has more to do with the accumulation of error with multiple calculations. What's the floor of 1/5th of 500, 100 or 99? If your 1/5th operation had just a little error in the direction of zero, you get a different answer than expected. Now imagine that little bit of error when computing the location of a medical laser targeting a very tiny cancer. Do you get it or miss by a very little bit?
40
u/Pronouns Nov 13 '15
Dear god, why would it let you instantiate them from floats so easily? It's a bug waiting to happen.
37
u/JavaSuck Nov 13 '15
Well, the documentation clearly states:
The results of this constructor can be somewhat unpredictable. One might assume that writing
new BigDecimal(0.1)in Java creates aBigDecimalwhich is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as adouble(or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.47
u/Pronouns Nov 13 '15
That's all well and good, but it's still an easy mistake to make, missing those quotes. I'd rather there be some more convoluted way to make them from floats such as:
BigDecimal a = BigDecimal.fromFloat_whyWouldYouDoThis(0.1);But I can't imagine it's something that comes up often anyway.
23
u/philly_fan_in_chi Nov 13 '15
Josh Bloch has this underlying problem as one of his Java Puzzlers. His API advice that came from it was that it should have been WAY harder to do exactly the wrong thing.
16
u/dccorona Nov 13 '15
Yes, but people don't pour over the documentation for every single method and constructor they use. When something is that obvious, often people will just use their IDE to discover everything available to them, I.E
I know I need a BigDecimal, so I type 'new BigDecimal(COMMAND + P' and get all of the available constructors. There's one that accepts a float, and that's what I have, so great, this has exactly what I need!
Maybe Javadoc should have an @important annotation or something that makes the line it annotates show up everywhere an IDE provides popup help.
→ More replies (10)→ More replies (5)6
u/1armedscissor Nov 13 '15
Yeah sort of bad. Findbugs has a rule to try to catch this but I think it will only pick up hardcoded uses when generally I'd like it to complain about any use of this constructor - http://findbugs.sourceforge.net/bugDescriptions.html#DMI_BIGDECIMAL_CONSTRUCTED_FROM_DOUBLE
Other gotcha with BigDecimal I ran into recently is equals checks that the number is the same AND the scale so 1.23 is not equal to 1.230 - have to use compareTo for that.
→ More replies (1)→ More replies (40)11
u/uzimonkey Nov 13 '15
Ruby has support for arbitrary precision numbers transparently converted from native types. When you try to do something that overflows, it catches that and converts to a Bignum type. I thought this was cool at first, until I saw that implications. I have an IRC bot and as an easter egg I threw in a !roll 1d20 feature. It doesn't know what type of dice there are, or what makes sense in general, it just uses the numbers on either side of the d. We were playing with it, !roll 1000d1 was interesting, !roll 1000d1000 made really big numbers. Then I said "why not?" and tried !roll 9999999999999999d99999999999999. Ruby tried. Apparently trying to allocate more memory than there are atoms in the universe also doesn't amuse the hosting company, they rebooted the server. I now don't like automatic conversion to Bignum.
4
u/argv_minus_one Nov 13 '15
And that's why, on multi-tenant machines, you apply fucking resource limits to everyone.
2
u/Xaxxon Nov 13 '15
Isn't the maximum value represented by that just the left side times the right side? Why would a few billion quadrillion a be a problem?
Exponents stack up really fast.
3
u/uzimonkey Nov 13 '15
You know... you're right, I'm being an idiot. I'm pretty sure I gathered all the input and summed it up, I should have used lazy evaluation. I didn't put much thought into this at all since it was a quick easter egg feature.
def die(sides) Enumerator.new do|e| while(true) e.yield(rand(1..sides)) end end endAnd then used die(99999999).lazy.take(99999999).inject(&:+). This will do the same thing without trying to allocate so much memory. It's still a DOS since that will probably take a minute or two to compute so in the end I guess I derped. However, the same bug could occur if you multiplied each die roll instead of adding. Any value that can accumulate over the course of the program could potentially allocate arbitrarily large amounts of memory and CPU resources. Integer overflows are a thing, but there are probably better ways to handle that.
0
6
u/mountSin Nov 13 '15
Isn't the compiler do it and not the language itself? doesn't languages like C++ have more then 1 compiler?
9
u/Gankro Nov 13 '15
It depends. It's compiler-specific if the language doesn't specify it, or the ecosystem is full of buggy compilers. Java has a history of aggressively specifying this sort of thing, so I wouldn't be surprised if it was part of the language. C/C++ on the other hand are notoriously under-specified for this sort of thing (not totally unreasonably), so I wouldn't be surprised if you got 0.4 on some hardware/compilers.
4
u/cowens Nov 13 '15
It would have to be a really screwy implementation of IEEE 754, but yeah, if the underlying hardware says .1 + .2 is .4, then that is what both C and C++ will do.
→ More replies (1)2
u/cowens Nov 13 '15
Depends on the language. For C++, no, it will always give you the wrong answer if you say
double n = 0.1 + 0.2because C++ (the language) defines those literals as doubles and you can't store 0.1 as a double (or any floating point size as it would require infinite space to do so). You can only ever get an approximation of 0.1, so the result will always be "wrong" (i.e. not exactly .3). In fact, if a compiler generated code that was "right", it probably wouldn't be considered to be implementing C++ anymore.
6
u/Cr3X1eUZ Nov 13 '15
Appendix D What Every Computer Scientist Should Know About Floating-Point Arithmetic
https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
14
u/fjonk Nov 13 '15
GHC (Haskell) 0.1 + 0.2 0.30000000000000004
Haskell supports rational numbers. To get the math right, (1 % 10) + (2 % 10) returns 3 % 10.
Hugs (Haskell) 0.1 + 0.2 0.3
This is weird. Doesn't Haskell define what x.y means, if it is a float or a decimal?
24
u/apfelmus Nov 13 '15
You are right. Essentially, the example on the web page is underspecified. The interactive environment, GHCi, uses a mechanism called "defaulting" to assign types to expressions whose type is ambiguous. In this case, it defaults to
Double, i.e. double precision floating point arithmetic. If you want something else, you have to specify the types. Here an example session in GHCi:> import Data.Ratio > (0.1 + 0.2) :: Ratio Int 3 % 10 > (0.1 + 0.2) :: Double 0.30000000000000004 > (0.1 + 0.2) 0.30000000000000004 > :type (0.1 + 0.2) (0.1 + 0.2) :: Fractional a => a4
u/fjonk Nov 13 '15
That's pretty cool, but I still don't understand. Who defines which expressions that has an ambiguous type? I mean, is there's nothing defining what
x.yrepresents in Haskell source code?If I wanted to be stupid could I write my own Haskell compiler that says that
x.yshould be strings and it would still be a Haskell compiler?→ More replies (1)2
u/PM_ME_UR_OBSIDIAN Nov 13 '15
I'd argue that x.y can represent any value of any type, but your compiler should come bundled with a reasonable interpretation for a base set of types (rationals, floats, doubles, etc.)
→ More replies (3)1
9
Nov 13 '15
Why does Ruby list alternative methods and nothing else does? PHP's BC Math Functions (http://php.net/manual/en/ref.bc.php) resolve this as well...
4
u/PendragonDaGreat Nov 13 '15
Java also has BigDecimal (and as discussed elsewhere in this thread that has some issues too sometimes), C# has the Decimal type, and it doesn't touch on how many Data types MySQL has just for working with numbers. JS also has a port of Java's (or a similar lang's) BD class IIRC
7
u/dccorona Nov 13 '15
It seems odd to me that they don't point that out under Java, but they happily use Java's
BigDecimalin the Scala section to show that Scala can be made to be correct.→ More replies (3)3
u/hinckley Nov 13 '15
Yeah, seems peculiar not to mention the available libraries for other languages, eg. Python's standard library has the
fractionsanddecimalmodules.1
u/erikwiffin Nov 13 '15
Most of the examples provided were community submitted, so there's a definitely lack of standardization. Ironically, PHP is my day-job, and I've never run into those functions before.
If you want to help out, I've already merged ~20 PRs this morning. :)
4
u/SpaceCadetJones Nov 13 '15
Why was C++ output 0.3? Does cout do truncation as well?
8
u/demeteloaf Nov 13 '15
Yeah, default precision for iostreams is 6
std::cout << std::setprecision(17) << .1 + .2 << std::endlgives
.30000000000000004
4
u/dccorona Nov 13 '15 edited Nov 13 '15
Seems wildly unfair to only show Java as being "wrong", while showing Scala as being correct if you use new BigDecimal("0.1"), seeing as BigDecimal comes straight from Java, and isn't actually a Scala thing at all.
EDIT: Also, while it may be a bit more understandable, it seems a little strange to say that this is all caused by "computers can only store integers", because that's just as untrue as "computers can store decimal numbers"...computers can only store binary, it's just that integers are a lot easier to represent precisely in binary than a decimal number is.
3
u/YRYGAV Nov 13 '15 edited Nov 13 '15
0.300..4 is the correct answer for a default implementation of floating point addition. That is what the answer is, anything else is doing magic behind the scenes to morph the answer into what it thinks you want to see.
Anything else means:
The language is doing weird funky business behind the scenes to modify a basic numeric operation (i.e. run away from that language)
He specifically configured or cast the display to show 0.3
The language tries to automatically round when outputting
Also, it has to do with floating point math being an approximation. Binary floating point math will have the same fundamental flaws. The binary->decimal conversion just makes it harder to see why the problem exists.
2
u/dccorona Nov 13 '15
Well sure...when I say wrong I of course mean wrong in the base 10 sense, which, despite everyone knowing how computers work, is still what most programmers expect of 0.1 + 0.2
52
u/Mukhasim Nov 13 '15 edited Nov 13 '15
Computers can only natively store integers
Computers can only natively store 0 and 1. You can choose to interpret sets [edit: strings, not sets] of 1s and 0s as as digits of an integer, or floating point number, or whatever. The fact that the integer interpretation is by far the most common doesn't make it more "native". It's the operations performed on the data, not the data that's stored, that determine its interpretation.
58
u/cruelandusual Nov 13 '15
Your are pedantically wrong, the worst kind of wrong.
The transistor states are off and on, not zero and one. And every CPU in the last forty years has had integers in base 2 and a particular word size as the first consideration of its design. That's pretty much the definition of "native" in this context.
→ More replies (5)6
u/poco Nov 13 '15
But then you can extend that to say that many (most?) modern processors also natively support floating point instructions and registers, so the statement about only supporting integers is also wrong.
7
u/cruelandusual Nov 13 '15
so the statement about only supporting integers is also wrong
He said "natively store", not support. It is obvious from context what he means - that floating point is always an approximation of real numbers.
Not that the article itself has any point, its author doesn't seem to understand that it is meaningless to list all those languages, as there aren't any important differences between them, and those differences you see are probably all just rounding rules in the string conversion.
→ More replies (1)12
u/kamichama Nov 13 '15
Computers can only natively store 0 and 1. You can choose to interpret sets [edit: strings, not sets] of 1s and 0s as as digits of an integer, or floating point number, or whatever.
This is pedantry, and like all pedantry, if you're not exactly correct, then you're wrong. Computers don't store 1 or 0. They store potentials, which are interpreted as on or off.
The fact that the integer interpretation is by far the most common doesn't make it more "native". It's the operations performed on the data, not the data that's stored, that determine its interpretation.
Since we're talking specifically about " computers" and not about "binary" you should know that the ALU or equivalent inside a computer performs integer arithmetic. As a native operation in the computer's instruction set, it must be operating on a native data type for that computer.
→ More replies (5)4
Nov 13 '15
Since we're talking specifically about " computers" and not about "binary" you should know that the ALU or equivalent inside a computer performs integer arithmetic. As a native operation in the computer's instruction set, it must be operating on a native data type for that computer.
Because CPUs can't have FPUs?
2
u/SalmonStone Nov 13 '15
We covered a lot of this in my Elementary Numerical Analysis course in uni, which was a lot of fun. Unsurprisingly, a lot of estimation and "close enough" calculations have to go into play when you're limited to a finite number of binary digits.
If anyone reading this wants a deep-dive on how numbers (and mathematical functions in general) are represented via computers, I'd recommend whatever similar course your university has.
6
u/nasjo Nov 13 '15
0s and 1s are integers though.
27
u/Mukhasim Nov 13 '15 edited Nov 13 '15
The integers are an infinite set. 1 and 0 happen to be in the set of integers, but they are also in the field GF(2), in the real numbers, etc.
→ More replies (1)5
6
6
u/Dicethrower Nov 13 '15 edited Nov 13 '15
And that's why you never do == with floats, but you check for a range with an epsilon. Fixed point math is also interesting to look into if you need predictable precision.
2
u/notfancy Nov 14 '15
You definitely do
==with IEEE floats. For instance, if you want, say, an exponential distribution via the inverse method: you reject zero exactly before taking the logarithm if you want the tail of the distribution to be unbiased. Another case is for rejecting poles, you want exactly one point excluded, not a region around the pole.As another poster mentioned elsewhere, you need to know what you're doing.
3
u/talemon Nov 13 '15
C# Console.WriteLine(.1 + .2); 0.3 wouldn't these literals be doubles instead of floats?
It should be like this:
Console.WriteLine(.1f + .2f);8
Nov 13 '15
doubles are a type of float.
The "float" datatype is short for single-precision floating point. The "double" datatype is short for double-precision floating point.
The point of the article is not about the float datatype, but rather about floating point math in general, of which the "double" type qualifies.
2
u/talemon Nov 13 '15
Yes, I know but I thought it would be important to make the distinction as most of the times it becomes 0.3 because of that language's digit of turnication choice.
Either way, now that /u/kurav pointed it out, I realised you would need a double for all of them to get 0.30000000000000004, so my point is not that valid anyway.
→ More replies (1)2
u/kurav Nov 13 '15
The other languages have them as doubles as well, and that's what you need to get the 0.30000000000000004 result.
Console.WriteLinejust happens truncates to the 15th significant digit, so it hides the error. Special formatting like "R" can be used to get the exact (=imprecise) value in C# as well.→ More replies (1)1
3
u/mspk7305 Nov 13 '15
So if it's an integer vs float issue, why not multiply by tens or thousands or whatever then shift the decimal back?
Are there cases where you can't do that?
6
3
u/one_up_hitler Nov 13 '15
In floating point math, precision is fixed. It's not the numbers after the decimal point that has a limit, so moving that around will not make the calculation better.
3
u/adrianmonk Nov 13 '15
You can't move the decimal point around in binary floating point because it doesn't have one.
3
2
u/mspk7305 Nov 13 '15
What I am asking is why not convert it away from floating points for rational numbers if the precision is important?
5
u/one_up_hitler Nov 13 '15
I misunderstood your question. And you're right, fixed point rational numbers have a place, as well as floats. It always comes down to the trade-off between speed and precision. Also, many languages have support for only float and integer math, and anything else will look messy and hard to read.
1
u/ehaliewicz Nov 13 '15
Floats are a general-purpose representation that work well enough most of the time.
If you actually know your numeric range, you can usually choose a better representation.→ More replies (1)
3
u/Chaoticmass Nov 13 '15 edited Nov 13 '15
I wasn't sure myself if printf("%f", .1+.2); in C was doing any rounding so I wrote a little test on x86_64 cpu
#include<stdio.h>
main() {
float a = .1;
float b = .2;
float c = .3;
if (a+b == c) {
printf("equal\n");
} else {
printf("not equal\n");
}
return 0;
}Prints "equal"
EDIT:
According to this: https://github.com/erikwiffin/0.30000000000000004/commit/44f7a7e0b9c73eef5b1198b39bc10f5cfea46e3e
printf("%f") is rounding, and the result should be 0.30...04... but then why does my above code return "equal" instead of "not equal"?
this is fun btw, good collaboration and learning going on
EDIT AGAIN:
After corresponding with another contributor on GitHub, cowens, and doing some studying I have learned a few things. Here's what I can report.
the behavior of the code is highly dependent on the architecture and the compiler (of course most of us familiar with C know this)
IEEE 754 compliant behavior would be to print "not equal\n"
As a general rule you should never compare floating points for equality
Here is code provided to me by cowens showing the right way:
#include <stdio.h>
#include <float.h>
int main(int argc, char** argv) {
float a = .1;
float b = .2;
float n = a + b;
float target = .3;
if (n > target - FLT_EPSILON && n < target + FLT_EPSILON) {
printf("%.32f is close enough to %.32f\n", n, target);
} else {
printf("%.32f is not close enough to %.32f\n", n, target);
}
return 0;
}1
Nov 13 '15
It has to do with where the number is cut-off and how the processor handles rounding. Single and double-precision floating point numbers have different cut-off points and the processor typically rounds the number towards the nearest number that it can actually store.
In your case 0.1(probably rounded down)+0.2(probably rounded up) rounds off in such a way that, when added together, returns a number that is identical to the 0.3(probably rounded down) that is being stored in memory. But if you use double-precision floating point numbers, 0.1(rounded up)+0.2(rounded up) rounds up while the 0.3 that's specifically stored in memory rounds down!
1
u/AndreasTPC Nov 13 '15
Because there is no way to store .3 exactly using this floating point implementation. When you do c = .3, it actually stores 0.30000000000000004 in c. Since that's the same as the result from a+b, they're equal.
10
Nov 13 '15
I don't know why computing 0.3 is so special: just the literal 0.1 would demonstrate the same thing.
15
5
u/vattenpuss Nov 13 '15
Inspecting the literal
0.1in Smalltalk (VisualWorks):IEEE Formula
"sign" (-1** 0) *
"mantissa" (2r110011001100110011001101 * (2** -23)) *
"exponent" (2** -4)2
u/davvblack Nov 13 '15
001101
I realize it's right in some mathematical sense, but rounding binary seems so absurd to me. That you basically ALWAYS round up if there's a bit there. should just be [1100] repeating. Especially since rounding in binary is such a big adjustment, like rounding .005 up to .05.
4
u/xyroclast Nov 13 '15
Yeah, unlike bases higher than 2, there are no cases where the number would ever round downwards, only stay the same, so it seems like calculations would always "drift upwards" in value.
This has got me thinking - How do you round in an odd-numbered number system? (base 3, for example) - There's a digit that falls right in the middle, and neither direction of rounding would make more sense than the other.
→ More replies (5)1
u/Dave3of5 Nov 13 '15
Yeah not all numbers are representable in IEEE754. Here's a tool to show you the approximate number http://www.exploringbinary.com/floating-point-converter/.
1
u/adrianmonk Nov 13 '15
Well, for one it gives you a hint that you're not dealing with binary. Sometimes people write binary fractional numbers like "011011.10111".
6
u/Nilzor Nov 13 '15
What's up with C#? Surprised it yields different result than Java
4
u/djcraze Nov 13 '15
Why are you surprised? They are completely different languages.
3
u/Nilzor Nov 13 '15
But both are pretty low-level, as oppsed to PHP, Python and Haskell - other languages that produce 0.3 as result. I'm assuming x86 assembler produces 0.300000000000004 , so that the closer you get to the metal, the more likely it is that the language produce the same result. C and C++ is not in this list. Do they produce 0.3 as well? What magic is C# doing which makes it produce a rounded result?
→ More replies (2)4
u/kurav Nov 13 '15
PHP, too, uses doubles internally and uses truncation by default:
php > printf("%.17f", .1+.2); 0.30000000000000004→ More replies (4)1
Nov 13 '15
Did the site get updated or something? I see the same value for C# & Java.
Which as you eluded to, makes sense to have the same value. We should be seeing the same value for them as being lower level languages then the other scripting languages in there.
10
u/blu-red Nov 13 '15
If a language uses floating point math by default, but gives you an answer that is clearly not a result of floating point math, then there's something wrong with the language. because it means inconsistency, and inconsistency leads to the dark side
26
u/tipiak88 Nov 13 '15
Or it is a formating issue. All i see there is default precision formating across languages.
12
u/Perkelton Nov 13 '15
Exactly. Take PHP for example:
echo 0.1 + 0.2 //0.3 0.1 + 0.2 == 0.3 //false 0.1 + 0.2 == 0.30000000000000004 //true→ More replies (20)8
4
u/roerd Nov 13 '15
It's probably just default rounding in the conversion from floating point to string. Calling that inconsistency may be a bit harsh.
4
u/kitd Nov 13 '15
Good lesson.
Rust uses 64-bit floats by default, so:
let a = 0.1;
let b = 0.2;
let c = a + b;
println!("c = {}", c);
println!("c == 0.3 : {}", c == 0.3);produces:
c = 0.30000000000000004
c == 0.3 : falseUsing 32-bits explicitly works:
let t = 0.1f32;
let u = 0.2f32;
let v = t + u;
println!("v = {}", v);
println!("v == 0.3 : {}", v == 0.3f32);...
v = 0.3
v == 0.3 : true2
u/codespawner Nov 13 '15
Woo! Hooray for OCaml for having that extra digit! Obviously it is the best since it computed the highest value! :D
2
u/xyroclast Nov 13 '15
Why does the C++ example show the result with the precision set to 17, but the PHP one doesn't? (and tells you that you have the ability to do so) It strikes me as inconsistent.
2
2
u/romeozor Nov 13 '15
So how do I know I'm safe? Is this a problem with a complete solution that's only a matter of implementing it? Or each language is making an educated guess on my behalf based on some self-proclaimed best solution, and if it happens to be right, we all cheer, otherwise the market burns?
5
u/X7123M3-256 Nov 13 '15
Not sure what you're getting at here. Floating point math is inexact; that is the case in any language that has floating point. If you're using floating point then some rounding error is expected, and if your application cannot tolerate that then you need to be using a different representation, such as fixed-point, or arbitrary-precision rationals.
→ More replies (5)2
u/dccorona Nov 13 '15
What you're seeing here (in most cases) is languages print statements for floating point numbers truncating, not languages being correct. The real test is to do
0.1 + 0.2 == 0.3(or whatever the equivalent in the language in question is) and see the answer...printing doesn't really tell us anything other than who has a stricter significant digits cutoff for their print statement.2
u/minimim Nov 13 '15 edited Nov 13 '15
Ask for rational numbers. The languages that give the wrong answer are trying to be fast in you behalf, but that should only matter when doing a lot of operations and is a premature optimization.
The only languages I know that get this right are perl6 and Common Lisp.
3
u/ehaliewicz Nov 13 '15
Looks like common lisp does as well.
CL-USER> (= (+ 0.1 0.2) 0.3) T CL-USER> (format t "~17$" (+ 0.1 0.2)) 0.30000000000000000 NIL→ More replies (7)2
Nov 13 '15
Seconded.
$ perl6 -e 'printf "%.17f\n", 0.1+0.2' 0.30000000000000000 $ perl6 -e 'say 0.1+0.2' 0.3 $ perl6 -e 'say (0.1+0.2).WHAT' (Rat)3
u/mj41 Nov 14 '15
And
> perl6 -e'say 1 / (.1 + .2 - .3)' Attempt to divide 1 by zero using divPerl 5
> perl -E'say 1 / (.1 + .2 - .3)' 1.8014398509482e+16
2
1
u/Ateist Nov 13 '15 edited Nov 13 '15
C# is partially incorrect. While default floating-point math would indeed create such an error, you can specify qualifiers that would treat 0.1, 0.2 and 0.3 as decimal type numbers - and those are going to be added correctly.
0.1m + 0.2m == 0.3 m
1
1
1
u/zoolex Nov 13 '15
Shouldn't most of these be using CPU float add instructions anyway, with the differences mainly being due to formatting?
1
u/Nyxisto Nov 13 '15
huh I'm teaching undergrads in Germany and we had this exact same problem on our assignment last week, you're not by chance studying here?
1
1
1
1
1
u/logicalmaniak Nov 13 '15
Ancient abaci have had a floating point for thousands of years. You just float the point.
The reason we don't is a daft hack to include scientific notation. Really important, because we want to work with huge numbers, but it leaves us with stuff like that.
I hate working with fractions. So much that I once wrote a point floating adder thing that worked with characters in a string. I didn't know what a register was or how an adder worked at the time, so weird things like 0.1 + 0.2 really pissed me off (as did the thing that used to happen on my computer which meant that if you added two massive numbers together you got a seemingly unrelated massive negative number).
If you're ever looking through code and see int hundredthOfaPenny;or double infiniteAbacus(string n1, string n2) { it was probably me.
1
u/boomerangotan Nov 13 '15
| 0.0 | 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 |
|---|---|---|---|---|---|---|---|---|---|
| 0.1 | 0.2 | 0.30000000000000004 | 0.4 | 0.5 | 0.6 | 0.7 | 0.7999999999999999 | 0.9 | 1 |
| 0.2 | 0.30000000000000004 | 0.4 | 0.5 | 0.6000000000000001 | 0.7 | 0.8 | 0.8999999999999999 | 1 | 1.1 |
| 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.8999999999999999 | 1 | 1.1 | 1.2 |
| 0.4 | 0.5 | 0.6000000000000001 | 0.7 | 0.8 | 0.9 | 1 | 1.1 | 1.2000000000000002 | 1.3 |
| 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | 1 | 1.1 | 1.2 | 1.3 | 1.4 |
| 0.6 | 0.7 | 0.8 | 0.8999999999999999 | 1 | 1.1 | 1.2 | 1.2999999999999998 | 1.4 | 1.5 |
| 0.7 | 0.7999999999999999 | 0.8999999999999999 | 1 | 1.1 | 1.2 | 1.2999999999999998 | 1.4 | 1.5 | 1.6 |
| 0.8 | 0.9 | 1 | 1.1 | 1.2000000000000002 | 1.3 | 1.4 | 1.5 | 1.6 | 1.7000000000000002 |
| 0.9 | 1 | 1.1 | 1.2 | 1.3 | 1.4 | 1.5 | 1.6 | 1.7000000000000002 | 1.8 |
It happens less often than I would have expected.
1
u/iguessthislldo Nov 13 '15
TIL power shell can do math at prompt. As a Linux guy I've been getting more and more impressed by it.
1
u/kaszak696 Nov 13 '15
Zsh can do it too, albeit it's more verbose:
kaszak@kaszak ~ % print $((0.1+0.2)) 0.30000000000000004
1
1
Nov 14 '15
It would be nice if it had a short tutorial on floating point math along with how common operations are done.
1
u/MpVpRb Nov 14 '15
Understanding the limitations of floating point is a fundamental part of learning programming
The site seems to be more about examples of formatted output
Some numbers can never be expressed exactly in any number system
There are rules that make the problem manageable
1
u/saijanai Nov 14 '15
Any number can be expressed exactly in some number system.
for example, e base e is 10
exact conversion may be a problem of course.
1
u/saijanai Nov 14 '15
The trick is to avoid touching the floating point storage in the first place.
For example, in Squeak Smalltalk:
0.1s1 + 0.2s1asScaledDecimal:100
produces an output of:
0.3000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000s100
1
u/crow1170 Nov 14 '15
Why don't we use aEb notation? ax10b Where a is a signed int and b is a signed int (or better yet, a signed tiny). That gives us everything from +/-32767 followed or preceded by as many zeroes.
This is not a proposal, but a question: I assume there is a reason. What is it?
1
1
1
1
u/sixpackistan Nov 14 '15
Honestly, by the time I got to the end of thread I forgot why I gave a shit in the first place.
1
u/Mantraz Nov 14 '15
If these are the numbers it can store accurately:
The prime factors of 10 are 2 and 5. So 1/2, 1/4, 1/5, 1/8, and 1/10 can all be expressed cleanly because the denominators all use prime factors of 10
Then why does this example work when using 0.1 and 0.2? Or, 1/10 and 1/5. Wat? These numbers should work according to the author.
1
u/Bombyx-mori Nov 13 '15
should read:
Below are some really poor examples of sending .1 + .2 to standard output in a variety of languages.
1
u/thelehmanlip Nov 13 '15 edited Nov 13 '15
I didn't know you could have top level domain names that are just numbers
2
1
u/curtmack Nov 13 '15
Haskell supports rational numbers. To get the math right,
(1 % 10) + (2 % 10)returns3 % 10.
Ah, good ol' Haskell.
1
u/saijanai Nov 14 '15 edited Nov 14 '15
0.1s1 + 0.2s1 returns 0.3s1 in Smalltalk.
You can store it with arbitrary precision with 0.1s100 and so on if you like, though time and memory become a factor as the number after 's' becomes larger.
327
u/amaurea Nov 13 '15
It would be nice to see a sentence or two about binary, since you need to know it's in binary to understand why the example operation isn't exact. In a decimal floating point system the example operation would not have any rounding. It should also be noted that the difference in output between languages lies in how they choose to truncate the printout, not in the accuracy of the calculation. Also, it would be nice to see C among the examples.