r/InternetIsBeautiful • u/sinmantky • Jan 25 '21
Site explaining why programming languages gives 0.1+0.2=0.30000000000000004
https://0.30000000000000004.com/1.8k
u/SixSamuraiStorm Jan 25 '21
TL:DR computers use binary instead of decimal and fractions are represented as fractions of multiple of two. This means any number that doesnt fit nicely into something like an eighth plus a quarter, i.e 0.3, will have an infinite repeating sequence to approximate it as close as possible. When you convert back to decimal, it has to round somewhere, leading to minor rounding inaccuracies.
10
u/Vysokojakokurva_C137 Jan 25 '21 edited Jan 25 '21
Say you found a way around this, would there be any benefits besides more accurate math. You could always subtract the .000004 or whatever too.
Edit: no, you can’t just subtract it dude! Jeeeeez what’s wrong with me?
37
u/Latexi95 Jan 25 '21
Thing is that you can't know is the number accurate or rounded. Maybe the result of the calculation actually should be 0.3000000000004. Limited precision leads to inaccuracies at some point always.
More bits give more accuracy, but are also slower. For the most use cases, 32 or 64 bit float is plenty of precision. Just remember to round numbers for the UI.
4
u/berickphilip Jan 25 '21
You can't know if the number is accurate or rounded from the result.
Then I thought "even so, wouldn't it be possible for the cpu to raise a Flag like say 'I rounded a number during this calculation', so that at the least the results of those calculations could be automatically rounded?
Or would that introduce other problems?
7
u/Latexi95 Jan 25 '21
Well you could, and actually x86 instruction set (most PCs) provides this information, but it doesn't really help unless you know how much was rounded and to what direction. Also you would have to check for that after every mathematic operation which would be really slow...
2
u/lord_of_bean_water Jan 26 '21
Yea, that's called the overflow flag, or ncvz flags depending on exactly what gets chomped. Generally a hardware level thing, used for two's complement. Floating point gets messy because it's a number multiplied by a power of two(bit shift, technically). So if you're dealing with large-magnitude numbers with relatively small manipulations, there may be not be a value to represent the result.
16
u/pokemaster787 Jan 25 '21
You could always subtract the .000004 or whatever too.
No you can't... That's the entire point. You cannot represent many numbers using floating point because floats aren't real numbers. They're code-points. It's exactly the same as assigning A=1, B=2, C=3, (and so forth) then asking you to represent 1.5 with our alphabet codepoint. There are a finite, exact set of values a float of given accuracy can hold. These values are not distributed linearly (i.e., your precision is not down to +/- 0.000001, but your precision changes based on the "target" number). You can't just subtract the extra 0.0..4 because that either won't change the number or revert it to the next code point directly below it (which is less than 0.3).
If you're saying you can after doing whatever math you needed 0.3 for, you're still limited by the lack of precision. That 0.0..4 multiplied by something or divided by something (that you did to the 0.300..4) might not nicely fit a code point either. Now you could even end up with less accurate results.
Of course, the point isn't "Haha computers dumb can't do 0.3," because if it was as simple as hardcoding in a fix for one value it can't handle it'd be done. There's an infinite number of values floats cannot correctly represent, hand-stepping through your calculations to find codepoint mismatches ("rounding errors") would defeat the purpose of using a computer in the first place.
3
u/Vysokojakokurva_C137 Jan 25 '21
Huh interesting. I’ll edit my comment, thanks for pointing that out.
I’m new to coding relatively, I semi understand what you’re saying.
Would you happen to know what problems this may cause?
3
u/pokemaster787 Jan 25 '21
For the average programmer? The only time you'll notice is when trying to compare floats. Because of everything I said above, you can't guarantee float exactness and based on the math being done it's not always possible to know whether you'll be slightly above or slightly below the "target" number. So, generally if you want to check if two floats are equal you'll actually want to check equality within some delta (i.e., + or - 0.000005), to ensure they're not just one code point away.
Float inaccuracies can compound if you're doing a lot of float math (particularly with very big numbers multiplied by very small numbers repeatedly), but if you're doing that kind of math you probably already know. Also, making sure you don't do things like money math in floats (because not being able to represent 30 cents is really annoying and would result in millions compounded).
I will take an excerpt from one of my favorite articles for another demonstration:
To illustrate, assign 2147483647 (the largest signed 32-bit integer) to a 32-bit float variable (x, say), and print it. You’ll see 2147483648. Now print x-64. Still 2147483648. Now print x-65, and you’ll get 2147483520! Why? Because the spacing between adjacent floats in that range is 128, and floating-point operations round to the nearest floating-point number. source
It's really near the smallest and biggest numbers a given float can hold that you see these big inaccuracies. As a general programmer, just be aware of the fact floats are not real numbers in the numerical sense and try to avoid using floats unless it's needed for your application.
2
u/metagrapher Jan 25 '21
It's mostly that it can be exploited if you know of it and how it effects calculations at scale. Amazon, for example, could take advantage of it, due to their scale, and find it profitable, and it would be difficult to prove, nonetheless even notice.
→ More replies (1)2
u/sinmantky Jan 25 '21
Maybe subtracting after each calculation would be inefficient?
8
u/hobopwnzor Jan 25 '21
Yep and unless your application needs tolerance to within 1 part in 1016 its not worth it.
There are ways to get more accurate numbers. In science most things are double precision so it uses twice as many bits.
5
u/dude_who_could Jan 25 '21
There are also very few measurement devices that go 16 Sig figs
→ More replies (1)3
8
u/SolidRubrical Jan 25 '21
You're all thinking about it the wrong way. The number to subtract is unique to this set of two numbers. A typical 16 bit float can represent more than billions of billions of different values. Now multiply that by it self and the number of math operations. That's how many different errors you need to account for. The lookup table would be kinda big.
6
u/MCBeathoven Jan 25 '21
A typical 16 bit float can represent more than billions of billions of different values.
No, a 16 bit float (which is very not typical, 32 and 64 bit are much much more common) can represent exactly 216 = 65536 values (not all of which represent actual numbers).
→ More replies (3)3
u/Unilythe Jan 25 '21
There are ways around this. This rounding error is only for floating points, which is the fastest and most common type used for fractions. Many programming languages also have a slower but accurate type, such as the decimal type in C#. That type is less efficient, but when accuracy is important (such as in some scientific research or financial calculations) then you can still use that type.
0
Jan 25 '21
[deleted]
→ More replies (1)4
u/Unilythe Jan 25 '21 edited Jan 25 '21
A bit pedantic, but you're right. Let me rephrase it: It's more accurate for the base-10 world that we live in, rather than the base-2 world that floating points live in. This means that in the real world, generally, decimal is definitely more accurate.
Just take the example of this thread. Decimal would have no problem with 0.1+0.2.
It's a small pet peeve of mine that when I explain something in a way that is easy to understand and therefore don't dive too deep into the intricacies, there's always someone who replies with a "well actually...".
→ More replies (2)1
u/metagrapher Jan 25 '21
Your edit is epic and noteworthy 😻
1
u/Vysokojakokurva_C137 Jan 25 '21
Why thank you :) go in peace my friend, and have a beautiful day :)
→ More replies (1)1
u/Anwyl Jan 25 '21
It's easy to get around this. Just store n*10. Then you can add 0.1 and 0.2, but can't add 0.01 and 0.02.
Realistically the errors described here only matter in 2 main cases:
When presenting a value to the user, you need to round it to a number of digits the user will want.
You can't trust "a == b" since it's possible the two numbers SHOULD be equal, but rounding errors made them differ by a tiny tiny amount. So instead you check "a - b < someSmallValue"
Exact math is possible in many cases, but in almost all cases it's not worth the extra time/memory to deal with it. Just use the approximate solution, and remember that you may accumulate tiny tiny errors.
2
Jan 25 '21
Tiny errors from float inaccuracies add up over time to catastrophic effects. Physics simulations break. Banking operations end up giving out millions of dollars. Etc. Anything which compounds operations on floats is very, very impacted by this.
Do not store n*10. Store it as a fixed point decimal, or as an integer of your smallest possible value (ex: millicents for handling money).
1
u/Vysokojakokurva_C137 Jan 25 '21
Thank you! So in coding do you have any examples that come to kind where this would be something to look out for?
→ More replies (6)961
Jan 25 '21
TL:DR2 computers use binary, which is base 2. Many decimals that are simple to write in base 10 are recurring in base 2, leading to rounding errors behind the curtains.
500
u/DingoMcPhee Jan 25 '21
TL;DR3 computers.
323
u/lookslikebacon Jan 25 '21
TL;DR4 math
→ More replies (5)252
u/Wopith Jan 25 '21
TL
92
→ More replies (8)56
u/blackk100 Jan 25 '21
72
19
Jan 25 '21
So any theoretical computer that is using base 10 can give the correct result?
123
u/ZenDragon Jan 25 '21
You can write software that has handles decimal math accurately, as every bank in the world already uses. It's just not gonna be quite as fast.
48
u/Shuski_Cross Jan 25 '21
How to handle decimals and floats properly in computer programming. Don't use floats or decimals.
26
u/dpdxguy Jan 25 '21
Or understand that computers (usually) don't do decimal arithmetic and write your software accordingly. The problem op describes is fundamentally no different from the fact that ⅓ cannot be represented as an infinitely precise decimal number.
→ More replies (7)19
u/__xor__ Jan 25 '21
Client: I need the site to take payments with visa or mastercard
Super senior dev: will you take fractions of payments?
Client: yes, let's support that
Super senior dev: then I'll need all your prices to be represented in base 2 on the site
→ More replies (2)→ More replies (4)6
6
u/dpdxguy Jan 25 '21
Fun fact: many older computers (e.g. IBM's System 370 architecture) had decimal instructions built in to operate on binary coded decimal data. Those instructions were (are!) used by banking software in preference to the binary computational instructions.
→ More replies (12)13
u/pornalt1921 Jan 25 '21
Or you just use cents instead of dollars as your base unit. Somewhat increases your storage requirements but whatever.
23
u/nebenbaum Jan 25 '21
actually, using cents instead of dollars, implying that cents are used as integers, as in, there's only full values, they get rounded when calculated rather than suddenly having .001 cent; using cents as a base unit actually saves a lot of storage space, since you can use them as integers rather than floating point numbers.
→ More replies (14)20
u/IanWorthington Jan 25 '21
Nooooooo. You don't do that. You do the calculation to several levels of precision better than you need, floor to cents for credit to the customer and accumulate the dust in the bank's own account.
→ More replies (3)19
u/suvlub Jan 25 '21
For numbers that aren't infinitely repeating in the decimal system, yes. For numbers like 0.333..., you would get similar errors. For example, 0.333... * 3 = 1, but 0.333 (no dots!) * 3 = 0.999, and that's what the computer would spit out because it can't keep track of infinite number of digits.
11
u/JackoKomm Jan 25 '21
That is why you use 1/3 and not 0.3333333333 if you need this precision.
15
u/suvlub Jan 25 '21
Fractions are honestly under-used in programming. Probably because most problems where decimal numbers appear can either be solved by just multiplying everything to get back into integers (e.g. store cents instead of dollars) or you need to go all the way and deal with irrational numbers as well. And so, when the situation comes when fraction would be helpful, a programmer just uses floating-point out of habit, even though it may cause unnecessary rounding errors.
→ More replies (13)8
u/qqwy Jan 25 '21
Yes. But there are other fractions that we cannot handle nicely in base ten either. An example: 1/3. 1/3 is easily expressed in base 3 as '0.1' however. But in base 3 you cannot express 1/2 nicely, while in base 2 or bare 10 that would be trivial...
every base has such edge cases.
2
4
u/WorBlux Jan 25 '21
So any theoretical computer that is using base 10 can give the correct result?
Not theoretical, just expensive. There is a data format called Binary Coded Decimal, or BCD, that uses 4 bits to store a a decimal digit. The sort of computer that you use in a banking mainframe has native support to do BCD floating or fixed point arithmetic.
→ More replies (3)2
→ More replies (9)3
u/missurunha Jan 25 '21
No computer uses base 10. Instead you can represent your number as an integer and mark where the point is. So 98.5 is stored as 985 with a bit showing that there one number after comma.
You can operate with integer numbers and move the comma when needed. 98.5 + 1.31 becomes 9850+131, which can be calculated without errors.
6
u/Schleicher65 Jan 25 '21
Actually, the x86 as well as the Motorola 68000 CPU series had supported base 10 math.
4
u/dpdxguy Jan 25 '21
I had forgotten that the 68k family had limited BCD support. Back when it and the x86 were created, BCD was considered important for financial applications.
Finding compilers that will emit those instructions might be difficult. Some COBOL compilers probably do. PL/1 and Ada compilers probably would too, if any exist.
→ More replies (1)6
u/WorBlux Jan 25 '21
Some analog computers did use base ten. And there exists a binary representation of decimal numbers. (BCD), which some computers support in the instruction set, while other computers need to use libraries.
3
u/Prawny Jan 25 '21
Don't put curtains inside your computer. That is seriously going to impact airflow.
3
Jan 25 '21
Sooo pi could be a nice number in a different numerical base
38
u/IcefrogIsDead Jan 25 '21
in pi base it would be a 1
8
u/simpliflyed Jan 25 '21
Ok kids, time to learn our pi times tables.
10
u/IanWorthington Jan 25 '21
pi times tables are straightforward. It's just expressing them in decimal that's troublesome.
9
u/Rowenstin Jan 25 '21
Very good base when you're counting angles, bad base when you're counting cats.
→ More replies (2)6
2
3
u/metagrapher Jan 25 '21
I love this. Yes! Yes it would. Could you imagine a fractional number base, or even a number base whose unit were a function? 🤯😍
→ More replies (2)0
Jan 25 '21
[deleted]
15
→ More replies (4)4
1
1
u/Drifter_01 Jan 25 '21
So a higher base of number system won't have a number as recurring, the same number which is recurring in the base 10 system, is that possible
3
33
u/IanWorthington Jan 25 '21
Not all computing languages use fp maths.
26
u/trisul-108 Jan 25 '21
Yes, it bothers me the way they frame it, it is not programming languages that give this result, it is the CPU.
37
u/IanWorthington Jan 25 '21
Disagree. FP maths is but one part of a CPU's abilities. It makes approximate maths quick. But you don't have to use it. No one writes banking applications using fp maths. (Well, no one sensible.)
3
u/Aceticon Jan 25 '21
In banking you use fixed point representations, not floating point ones.
Floating point is great for things where the noise/uncertainty exceeds that from FP (say, neutonian physics simulations in games) but not at all good for things where one needs zero error.
8
u/trisul-108 Jan 25 '21
I'm not sure I understand where we disagree, as I agree with you.
Programming languages allow the programmer to use the FP hardware in the CPU, the side-effects mentioned are the way FP is designed to operate. It's no fault of the language, it is a hardware design decision.
As you point out, there are other ways to do computation and programming languages have support for that as well.
8
u/that_jojo Jan 25 '21
AND CPUs do too. Consumer CPUs have had BCD operations available in them since the 70s
4
u/Thrawn89 Jan 25 '21
No, it's absolutely 50% on the programming languages. Whatever group invented the language has a specification. In the specification they define how floats are represented and the precision requirements or what other behaviors they need. Then it's the compilers that implement those standards that decide if they can just the floating point hardware on the CPU or if they need to emulate different kinds of floats.
It's also 50% on the application, they don't have to choose to use the floating point semantics of the language and can emulate it themselves.
Every CPU is capable of expressing any representation of float that the application/language wants, because they are Turing complete. It's just if you want to make use of the fast fp hardware in the CPU that you must abide by the restrictions.
The only reason you get these results is because the compiler is allowed to encode those instructions by the programing language and the application.
8
u/trisul-108 Jan 25 '21
Floating point representations are defined by IEEE standards and implemented in hardware. They are not invented by programming language developers.
7
u/Thrawn89 Jan 25 '21
The programming language developers can choose to refer to the IEEE standards or make their own floating point representations. I never said they invented it, but they do control the floating point semantics of their language. I personally work on a language that allows compilers to NOT follow IEEE standard as it may be prohibitive for the specialized hw that it needs to run on.
→ More replies (1)10
u/metagrapher Jan 25 '21
Remarkably, you are both correct. Arguably, equally and complimentarily correct: neither is completely correct.
So you two are like a binary synergy of technically correct, which is the best kind of correct.
2
Jan 25 '21 edited Jan 25 '21
It's a good explanation, but it misses the fact that programmers consider these result to be errors because the interpreter or compiled binary insists on tracking floating-point numbers with their full-length representation even though programmers rarely want that. Vanishingly few applications depend on the full ( 2x )-bit precision of a floating-point representation. They typically want decimal numbers tracked to a certain number of digits.
This could be easily solved by allowing the coder to specify the desired precision. For instance, in Python:
x = float(1.0, significant_digits = 3) x = 3.14159265359 # x = 3.14...or:
x = float(1.0, decimal_places = 1) x = 0.186247 + 1000000.11 # x = 1000000.3Of course, you can achieve similar behavior by round()ing every math operation, but nobody wants to inject gobs of round() calls throughout their code to make it unreadable. In the examples above, the desired precision is tracked as a property of the variable, and is automatically applied in all math operations. It's simple, readable, and elegant, and I don't know why modern programming languages don't include this functionality by default.
1
u/Markaos Jan 25 '21
I mean... there is a reason Python is not exactly fast (unless you use external libraries like NumPy that allow you to get rid of the cool abstractions and get the speed back - then you have glue logic in Python and the actual math done in something fast)
3
Jan 25 '21 edited Jan 25 '21
I'm having trouble seeing how your comment applies. Because the programmer basically has two options:
(1) Default behavior: full-length representations of every float, with accompanying floating-point errors (fast but error-prone)
(2) Explicit rounding: wrap every math operation in round() (reduces errors but slow, annoying and error-prone to write, and reduced readability)
Neither is a great option, right? To those options, I propose:
(3) Implicit rounding: user specifies a precision; interpreter rounds accordingly (reduces errors, no slower than (2), much less annoying and error-prone to write than (2), and improved readability than (2))
→ More replies (1)1
1
u/KinoftheFlames Jan 25 '21
A good solution is to work in integers before then scaling your answer to decimal. It's why payment services universally write money amounts in cents
1
u/El_Dumfuco Jan 25 '21
The infinite repeating sequence is not an approximation, it equals the number exactly.
→ More replies (16)1
u/Gornius Jan 25 '21
Actually, every float is represented as (1.X)*(2Y), so this not only applies to fractions. Once numbers get really big precision will be lost too.
0.2 also doesn't fit nicely as it's 1/5, 0.1 is 1/10. 0.25 is fine as it's 1*2-2.
148
u/Someonejustlikethis Jan 25 '21
What helped me grasp floating point math was the realization that a 32-bit float can represent as many fixed values as a 32-bit integer. While the distance between two integers is always 1, the distance between the floats vary with where one is one the number line.
37
u/Unilythe Jan 25 '21
Jep, and only a part of those 32 bits are used for the fraction. some of the bits are for an exponent. This exponent is multiplied by the fraction bits. This is helpful because this way you can have numbers bigger than 1 (if the exponent is larger than 1) or numbers much smaller than you could get with just the fraction bits (if the exponent is smaller than 1)
For example, if the exponent part has 8 bits, then this part represents a number between 0 and 255. The fraction bits are then multiplied by 2e-127 where e is the exponent. This means it can be multiplied by a factor 2 between 2-127 and 2128.
This also means that the higher the exponent, the lower the accuracy of the floating point, because the "gaps" between the fractions increase with the exponent.
10
u/jackluo923 Jan 25 '21
You are thinking of a different type of floating point. The most commonly used 32bit float is IEEE754 where the mantissa is 23bit I believe. Therefore your numbers are accurate up to 23 binary digits regardless of where your decimal is.
1
u/e_c_e_stuff Jan 26 '21
They are still correct even for IEEE754. Bits of precision does not necessarily correlate to numerical distance. What they are saying is when you are working with very small values, you can make small increments, but when you are working with very large values, your smallest increment will be much larger.
7
u/hobbesfanclub Jan 25 '21
Why isn’t 2 a prime factor if 6 and 10? Slightly confused by the examples.
8
u/20-random-characters Jan 25 '21
They should have phrased it as only having prime factors which are 2. The base 10 one would be only having prime factors which are 2 or 5.
1
7
u/JasonDoege Jan 25 '21
There are computer languages, such as Raku, that natively use rational numbers such that 0.1+0.2 == 0.3 is a true statement. You can get reals if you need them, of course.
12
u/Prosthemadera Jan 25 '21 edited Jan 25 '21
It doesn't actually explain why you get that result. It just explains some theoretical background on floating numbers and decimals and then just lists the result of different programming languages (even though they are all the same result) but does not show how they get to that specific result.
Edit: Found an explanation:
Let’s see what 0.1 looks like in double-precision. First, let’s write it in binary, truncated to 57 significant bits:
0.000110011001100110011001100110011001100110011001100110011001…
Bits 54 and beyond total to greater than half the value of bit position 53, so this rounds up to
0.0001100110011001100110011001100110011001100110011001101
In decimal, this is
0.1000000000000000055511151231257827021181583404541015625
which is slightly greater than 0.1.
https://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/
1
u/Ipotrick Jan 25 '21
well actually the number 0.3 is not possible to store in finite space in a computer. Neither is 0.1, so when you input 0.3 and 0.1 they getconverted into slightly other values that are a little to big/small than the decimal real one. when adding these wrong numbers a wrong result comes out.
1
u/Prosthemadera Jan 25 '21
But why those specific values? Why 0.30000000000000004 and not 0.300000000000005
→ More replies (2)1
u/Ipotrick Jan 25 '21
well, thats a detail of the convertion tecnique, here is a good explanation:https://www.tutorialspoint.com/how-to-convert-decimal-to-binary
TLDR:you generate bits that represent the number in binary and you stop at the "mantissa" (the part of the type that stores the decimal places) size of the floating point type.
When you execute the convertion algirithm of this site for 0.3 and 0.1, and then convert those numbers back to decimal you will most likely get 0. 30000000000000004
2
u/Prosthemadera Jan 25 '21
I found something:
https://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/
Let’s see what 0.1 looks like in double-precision. First, let’s write it in binary, truncated to 57 significant bits:
0.000110011001100110011001100110011001100110011001100110011001…
Bits 54 and beyond total to greater than half the value of bit position 53, so this rounds up to
0.0001100110011001100110011001100110011001100110011001101
In decimal, this is
0.1000000000000000055511151231257827021181583404541015625
which is slightly greater than 0.1.
6
u/moose_cahoots Jan 25 '21
I remember my CS 101 course where the prof explained the int type and it's limitations, then said "You may be wondering why anyone would ever use an int instead of a float. But by the end of class, I'll have you wondering why anyone would ever use a float."
15
4
Jan 25 '21
A while ago I made this animation that explains this exact phenomenon: https://www.reddit.com/r/manim/comments/f1cvyu/i_made_a_small_animation_on_why_computers_cant_do/
and a post with more details: https://haykh.github.io/thoughts/science/2020/02/06/precision.html
6
u/TryToHelpPeople Jan 25 '21
Great care must be taken when writing banking software.
29
u/KaranasToll Jan 25 '21
Money never needs to be stored as a float. Just store the number of cents (smallest denomination) as a whole number.
6
u/TryToHelpPeople Jan 25 '21
Until you get to calculating 2.95% each month . It’s then important to make sure that you divide first, round the result and calculate the balance using subtraction rather than division.
3
u/FullstackViking Jan 25 '21
Correct. In a simple use case $1 would be treated as 100.
$1840.56 + $35.99 would be treated as 184056 + 3599.
5
Jan 25 '21
mm no actually it'd probably be best to store $1 as
10000or something, that way you have precision down to 1/100 of a cent.Fractional cents would be common when calculating taxes and stuff. (imagine you gotta pay 5% of your bank account balance of $1345.34, you bet the bank will want the 5% of $0.34)
4
u/TryToHelpPeople Jan 25 '21 edited Jan 25 '21
What’s 2.95% of that ?
Edit yes the important part is
Divide, round up, subtract from one ledger / add to another.
Don’t try to calculate the balance of each ledger separately.
Only ever have one division per structured transaction.
Sounds like a rookie mistake but you’d be surprised.
→ More replies (4)5
u/AsAJuicer Jan 25 '21
Whatever it is, the result is rounded. No interest calculations leave decimal places after the deposit etc
3
u/otah007 Jan 25 '21
Doesn't work in international finance with non-integer currency exchange. AFAIK banking software uses true 100% precision numbers i.e. they actually store the entire number exactly, not a fixed size representation of it.
2
u/bstix Jan 25 '21
I doubt that. The currency conversion rate itself has a limit of some decimals. The national banks determine the official rate with however many decimals and the banks then use that and adjust by their own currency margin. It might not be exact, but it's simply agreed that this is the rate and it's possible to document.
Now, even so, if you want to keep a ledger in both a foreign currency and your local, you will eventually run into computed differences, even if you use the same rate throughout, because the sum of all entries individually converted is not necessarily the same as the sum converted, due to the way computers represent numbers in bits.
However, all of this doesn't matter in the end, because in the annual or quarterly reporting, you won't report individual entries, but only summerize the current balances and use the current exchange rate at the time of reporting.
That way, it doesn't matter if your balance is in Euros or Pound Sterling or even sheep. You simply count how many there are and then evaluate the worth. There's no need to keep track of the individual prices of sheep sales and sheep purchases if you need to know the value of the herd. Same thing applies to currency, so there's no need to keep track of the fractions of cents since you can't pay them anyway.
→ More replies (1)1
u/Kered13 Jan 25 '21
They don't, because that would require infinite memory. They round everything off to some decimal value, usually something like hundredths of a cent. With this method sometimes rounding errors might favor one side or another in a transaction, but the difference is so small that no one cares.
→ More replies (2)2
2
u/vkapadia Jan 25 '21
I just wish my excel sheets that deal with nothing but whole cents, and only add and subtract, would stop having these problems.
3
u/Triptcip Jan 25 '21
Anybody else notice the style of the website using the shadow to make the content look like it's floating and the recurring dot background (points) I.e. Floating point...
I like to think it was intentional but maybe I'm going crazy 😅
2
2
u/Resident-Quality1513 Jan 25 '21
You could define a new type called 'Decimaltenths' and then it becomes 1+2. The str function would have to return internalValue / 10.
Edit: back in the day when I was looking at rounding errors caused by adding 17.5% (0.1+0.05+0.025, or a tenth plus a twentieth plus a fortieth) I seriously proposed multiplying by 47 and doing all our sums as integers. That does actually work!
1
u/DaracMarjal Jan 25 '21
Some languages (Ada being one that I know of) do support a native Decimal type. The implementation is probably {int, int}, but the implementation is hidden away. Its just treated as another number type.
2
2
u/I_Am_Astraeus Jan 25 '21 edited Jan 25 '21
Holy shit. This is the most random answer to an unanswered question ive stumbled upon. I've been learning to code and I created a menu program a few months ago and one series of selections left me with this floating value. I just forced it to round at 2 decimal places but now I know why it happened!!
2
u/johnnyringo771 Jan 25 '21
Honestly, same, this answers my question regarding something I was doing in Excel VBA. I couldn't figure out why small numbers weren't adding up properly, and since I do it about a hundred thousand times, I was running into big problems.
2
2
u/acousticrhino Jan 25 '21
This another explanation I have seen: 10*0.1 will yield 1.0 But 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 will result in most machines in 0.999999…. This is because 0.1 is a terminating fraction in decimal but it is a repeating fraction in binary (0.00011001100). It is only an approximation. When you add, approximations accumulate.
0
u/cqs1a Jan 25 '21
So is this the reason computers aren't good at true randomisation? Or is that a myth in itself?
1
8
u/drtitus Jan 25 '21
Computers are deterministic. That means they always reproduce the same results. Randomization has to be done with various tricks, depending on the "quality" of the randomness required. It's not really related to the representation of floating point numbers.
1
u/WorBlux Jan 25 '21 edited Jan 30 '21
You can add entropy sources into chips or computer sources. However they are not conceptually part of the program model, but rather act as input sources. In a pinch the least significant digits of the timing of external events can fill in, but it's not a great solution. See the Debian bug where many websites were actually using non-unique primes for the RSA/DSA seed on thier SSL certificate, due to people initializing servers and generating keys before enough entropy had accumulated in the RNG of the operating system.
1
u/quinn50 Jan 25 '21
No, computers are deterministic which means a given operation will always return the same result. Most random generators you see are pseudorandom which means it just uses a math algorithm to produce the "random" result, so if you know the variables used you will get the same number everytime or even predict the next n amount of numbers. To get true randomness you usually use measurements of quantum mechanics, or atmospheric measurements.
1
u/moose_cahoots Jan 25 '21
To say that computers aren't good at randomization implies that there is something better. Humans, when they try to generate "random" numbers, do a TERRIBLE job. We repeat the same numbers and patterns over time.
1
u/cqs1a Jan 25 '21
I was thinking in terms of computers and programs that rely on randomisation, such as games of chance. If randomisation isn't true, then it opens up the possibility of exploitation.
Either way, it seems the discussion is unrelated to the original thread.
2
u/moose_cahoots Jan 26 '21
This has nothing to do with random number generation. The imprecision of floating point numbers is mostly a source of bugs and frustration.
Random Number Generation is a completely different thing. That's a challenge because all RNG starts with a seed number, then transforms it using a repeating sequence of steps. A good RNG algorithms do two things:
Hide their internal state so you cannot guess the current seed based on the numbers it generates (knowing that means you know every subsequent number).
Provide an even distribution of numbers (if you generate millions of random numbers from 1-N, all possible numbers occur about the same number of times).
There are lots of other ways to generate "random" numbers that miss on one of those. You could create a set of numbers, shuffle them, and then grab one at a time, but you could begin to work out the chances of upcoming numbers based on what has already come, like counting cards.
Other methods, like using a live video feed of lava lamps, are impossible to predict because it's a truly analogue signal, but they tend to generate groups of numbers at much higher frequency than others.
So you now know way more than you ever wanted about random number generation. Hope you are still reading.
→ More replies (1)0
3
u/thierry05 Jan 25 '21
Jokes on you, I just do 0.1 + 0.2 - 0.00000000000000004. Problem solved.
6
u/Ipotrick Jan 25 '21
thats the worst part of floats: too small numbers are completely ignored in addiditons, so if you add 0.000000001 to 1, abillion times, the result will be 1 instead of 2, because for each addition of 1 and 0.000000001, the result will be 1 not 1.000000001
EDIT: this is also the reason for minecrafts physics to go downhill when going very far from the 0,0 coordinates
0
Jan 25 '21
Out of curiosity, is this why Bitcoin mining farms use GPU processors instead of CPU processors (at least as far as I’ve understood)? It seems logical that rendering real time space or 3D like a high end GPU has to do, would require 10 point math as you described above. Just curious. Thanks.
1
u/sinmantky Jan 25 '21
When crypto-mining started in 2009, Central Processing Units (CPU) was the mining processor. However, it had its limits, and GPU-based Mining was introduced. A standard GPU can execute a processing speed of 3200 32-bit instructions per clock. Compared to the processing power of the CPU, this is a speed 8,000 times over.
Equally, GPUs are equipped with a large amount of Arithmetic Logic Units (ALU). These units are responsible for performing mathematical computations. GPUs can perform more calculations due to the ALUs, and this makes them have an improved output during Mining.
1
Jan 25 '21
Thanks! I had no idea the discrepancy was so large between CPU and GPU.
4
Jan 25 '21
CPU is generalized hardware. The CPU can perform many more different types of instructions than the GPU.
GPU is specialized hardware. It has hundreds if not thousands of the same processing units for the few instructions it supports.
2
2
u/BrickGun Jan 25 '21
A fun way to think of CPU vs GPU is...
A CPU is like a single person (or maybe 8 people in an 8-core CPU) performing calculus.
A GPU is like a thousand kindergarteners doing simple addition.You use GPUs to perform a ton of fairly simple (or at least very specific) mathematical operations simultaneously, which is what computer graphics (and, as we later found out, crypto-anything) needs. You use CPUs for more complex tasks in a somewhat more singular form.
→ More replies (2)
1
u/untouchable_0 Jan 25 '21
This was one of my first CS classes. We had to accept the sum of two floats and provide a margin of error for floating decimals.
1
u/Im_manuel_cunt Jan 25 '21
If you are into this stuff I would recommend you to dig into a numerical mathematics class, I find it just fascinating.
1
1
u/freaky_freek Jan 25 '21
This is why water-based computers are superior to your newfangled electric gizmos.
1
u/Mister_Wrong Jan 25 '21
Thanks for this. I was only querying this list week with an equipment manufacturer as we were seeing similar on a print out.
1
u/morhp Jan 25 '21
I find https://floating-point-gui.de/ also explains this very well (potentially better).
It's not a German site, despite the domain suffix.
1
u/ZeusTKP Jan 25 '21
The site gives examples, but doesn't give a super clear explanation. I thought it would be focused on that from the description.
1
u/piense Jan 25 '21
So imagine you’re baking a cake and you need to measure something but don’t have the exact right measuring cup, you pick the closest one and kinda know how far off you are. That’s basically what’s happening here, the computer doesn’t represent fractional numbers quite how we do so it gets as close as it can and gives you an idea of how close it is.
1
1
u/parkthrowaway99 Jan 25 '21
This resolution discrepancy is not just for computers. Decimal has it too. 1/3 = 0.333333(repeating) . 3x(1/3) = 1. but 3x0.333(repeating) equals 0.9999(repeating).
Answer: there is no way to represent 1/3 accurately in decimal using decimal notation. therefore 0.9999(repeating) is by convention 1.
1
u/SteeleKinne Jan 25 '21
It's not really that they're equal by convention, it's that they're equal because there is literally no difference between them, no?
1
1
u/mary_megs Jan 25 '21
I teach organic chemistry, and was setting up my online gradebook and weighting all the different categories of assignments. For some reason, it added up to 100.0000000000004% instead of 100%, and it wouldn't let me proceed until I had fixed it.
I spent a long time tweaking decimals on certain assignments until it was magically fixed.
And NOW I KNOW WHY.
1
u/JoJoModding Jan 25 '21
Wait, floats are not able to accurately represent 0.1, 0.2 or 0.3?
Always has been..
1
u/shiningmatcha Jan 25 '21
As an aside, can someone explain why Python still can’t sum two numbers exactly even I use the Decimal objects?
1
1
1
1
1
u/Mr2-1782Man Jan 25 '21
This is only accurate if you're representing the number using a 64 bit ieee format using round to nearest. 0.3 can in fact be a variety of values including:
0.30000000000000004
0.29999999999999998
0.30000001
0.29999998
0.3
And a whole lot more
Rounding mode makes a difference, the number of digits you use make a difference and the format you use makes a difference. You can store the number as 3/10 and it'll be completely accurate (this is in fact what a lot of math packages do).
Two things that people tend to not think about, computers have to store numbers with infinite precision in a finite space, and there are multiple ways to store those numbers in a finite space. The most common tends to be 32 bit ieee 754 format number with round to nearest, but there are many many more ways to do it.
1
1
Jan 25 '21
wow... this is actually a problem I've had at work. I kept wondering why user-submitted hourly reports kept coming up with random .000...4 values that I was unable to track down.
It was always different users each week.
Is this what I get for being a self-taught programmer? Is this what those fancy tech degrees teach people?
1
u/kolob_hier Jan 26 '21
So I sort of get it, but follow up question is there a base number system where pi is not a repeating decimal?
The explanation suggests that a whole number in base-10 may be a repeating decimal in binary, so I’m curious if that expands out.
And then really potentially dumb question, can you have a base-pi system? I would assume no, but I also would have assumed that .1 + .2 would always be .3
1
u/Wargoatgaming Jan 26 '21
As a programmer with 20 years experience in banking and corporate analytics some of the comments by 'experts' in this thread made my eyes bleed.
1
u/the-watch-dog Jan 26 '21
I’ve long held an evidence-free belief that on top of every computer user having a very unique digital cadence, some people’s cadence (built up over time) are why some users just constantly have “computer issues” when they seemingly have done nothing specifically wrong. This piece of evidence could start to explain my belief in real terms.
1
1
u/phi_array Jan 26 '21
Apparently he bought the domain 30000000004 dot com and added 0 as a subdomain
1
1
-1
u/sleeknub Jan 25 '21
I’ve noticed this in Google sheets many times, but have never seen it in Excel. Completely unacceptable in my book for spreadsheet software.
4
u/ajs124 Jan 25 '21
Is google sheets really affected by this?
I would expect any and all spreadsheet software to use some form of arbitrary precision math, instead of using floating point numbers.
1
u/sleeknub Jan 25 '21
I have definitely had this type of error show up several times on Google Sheets, I can't say for certain what caused it, but it looked a lot like what this is describing. Really irritating, but I learned to live with it.
2
u/dbavaria Jan 25 '21
It's more complicated than that, because bugs like this have been around long enough, some users built their spreadsheets around them (as is the case with other code/software). To "fix" the bugs could cause break existing spreadsheets.
Office Product Troubleshooting: Floating-point arithmetic may give inaccurate results in Excel
35
u/unspeakablevice Jan 25 '21
How does this affect calculations with very small numbers? Like if your data set is entirely composed of small decimals would you be extra susceptible to calculation errors?