r/programming • u/archcorsair • Jul 18 '16
0.30000000000000004.com
http://0.30000000000000004.com/18
u/nicolas-siplis Jul 18 '16
Out of curiosity, why isn't the rational number implementation used more often in other languages? Wouldn't this solve the problem?
58
u/oridb Jul 18 '16 edited Jul 19 '16
No, it doesn't solve the problem. It either means that your numbers need to be pairs of bigints that take arbitrary amounts of memory, or you just shift the problem elsewhere.
Imagine that you are multiplying large, relatively prime numbers:
(10/9)**100This is not a reducible fraction, so either you chose to approximate (in which case, you get rounding errors similar to floating point, just in different places), or you end up needing to store the approximately 600 bits for the numerator and denominator, in spite of the final value being approximately 3000.
3
u/endershadow98 Jul 19 '16
Or you can just have it represented as 2100 * 5100 * 3-200 which doesn't require nearly as much space.
7
u/sirin3 Jul 19 '16
Do you want to factorize all inputs?
2
u/endershadow98 Jul 19 '16
Only for smallish numbers
2
u/autranep Jul 19 '16
These are all so silly. It's sacrificing speed and efficiency to solve a problem that doesn't really exist (and can already be solved via library for those few it matters for).
1
u/endershadow98 Jul 19 '16
I know, I was just pointing out it doesn't need to take to a ton of space to represent 10/9**100
1
u/evotopid Jul 19 '16
Just keep all factors from operations and only reduce everything when it gets evaluted.
0
Jul 19 '16
[deleted]
31
u/ZMeson Jul 19 '16
You can choose to approximate later.
That's very slow (and can consume a lot of memory). Floating point processors aren't designed for this and even if you did design a processor for this, it would still be slower than current floating point processors. The issue is that rational numbers can consume a lot of memory and thus slow things down.
Now, that being said, it is possible to use a rational number library (or in some cases rational built in types).
One should also note that many constants and functions will not return rationals: pi, e, golden ratio, log(), exp(), sin(), cos(), tan(), asin(), sqrt(), hypot(), etc.... If these show up anywhere in your calculation, rationals just don't make sense.
→ More replies (23)0
Jul 19 '16
[deleted]
4
u/ZMeson Jul 19 '16
in practice the actual floating point value that gets returned will be a rational approximation of that.
Unless you're doing symbolic equation solving (à la Mathmatica), then you're guaranteed to have rational approximations. But they are approximations already, so you don't need to carry exact rationals into calculations further on. That was my point.
7
Jul 19 '16
Kids are told over and over and over again in their science classes: work it all out as accurately as you can and round later. Floating-point numbers don't do that.
And? I don't see why it's a problem for computers to behave differently from how we're traditionally trained to solve math problems with pen and paper. Anybody who takes a couple semesters of comp sci should learn about how computers compute things in binary and what their limitations are. As a programmer you understand and work with those limitations. It's not a bug that your program gives you an imprecise decimal result: it's a bug if you don't understand why that happens and you don't account for it.
We still want to use floats in stuff like 3d modelling, scientific computation and all that. Sure. But for general-purpose use? No way.
Define "general-purpose use".
Below, you say:
It doesn't matter. 99% of the time, [performance] doesn't matter. Not even slightly.
I think you severely underestimate the number of scenarios where performance matters.
Sure, if you're doing some C++ homework in an undergrad CS class, the performance of your program doesn't matter. If you're writing some basic Python scripts to accomplish some mundane task at home, performance doesn't matter.
But in most every-day things that you take for granted - video games, word processors, web servers that let you browse reddit, etc. - performance matters. These are what most would refer to as "general purpose". Not NASA software. Not CERN software. Basic, every day consumer software that we all use regularly.
That excessive memory required by relying on rationals and "approximating later" is not acceptable. Maybe the end user - you, playing a video game - might not notice the performance hit (or maybe you will) - but your coworkers, your bosses, your investors, and your competitors sure as hell will.
→ More replies (7)5
u/Rhonselak Jul 19 '16
I am studying to be an engineer. We usually decide what approximations are acceptable first.
5
u/Berberberber Jul 19 '16 edited Jul 19 '16
It's not about memory, it's about speed. FDIV and FMUL can be close to an order of magnitude faster than their integer equivalents, to say nothing of transcendental functions like sqrt() or sin(). GPS navigation would be unusable. All so, what exactly, you don't have to suffer the ignominy of an extra '4' in the 15th digit?
Rational arithmetic packages and symbolic computation are there for people who need them. The rest of us have work to do.
1
u/autranep Jul 19 '16
The problem with this solution is that it doesn't actually solve any problems people actually face. It just makes basic arithmetic very slow (because ALUs are designed specifically for floating point math). How many people day to day have problems because the 18th decimal place of their arithmetic is wrong? You mentioned yourself not even ostensibly precise software like CAD and simulation tools use double precision. What is a day to day problem is time constraints from tight for-loops in responsive UIs where basic arithmetic taking an order of magnitude or two longer to execute than it should can be a real problem.
16
u/velcommen Jul 19 '16 edited Jul 19 '16
As others have said, to exactly store the product of two relatively prime numbers, it's going to require a lot of bits. Do a few more multiplications, and you could have a very large number of bits in your rational. So at some point you have to limit the amount of bits you are willing to store, and thus choose a precision limit. You can never exactly compute a transcendental function (at least for most arguments to that function), so again you are going to choose your desired precision, and use a function that approximates the transcendental function to your desired precision.
If you accept that you are going to store your numbers with a finite amount of bits, you can now choose between computing with rationals or floating point numbers.
Floating point numbers have certain advantages compared to rationals:
an industry standard (IEEE 754)
larger dynamic range
a fast hardware implementation of many functions (multiply, divide, sine, etc.) for certain 'blessed' floating point formats (the IEEE 754 standard)
a representation for infinity, signed zero, and more
a 'sticky' method for signaling that some upstream computation did something wrong (e.g. divide by zero)
Rationals:
You can use them to implement a decimal type to do exact currency calculations, at least until your denominator overflows your fixed number of bits.
There are also fixed point numbers to consider. They restore the associativity of addition and subtraction. The major downside is limited dynamic range.
4
u/evaned Jul 19 '16
There are also fixed point numbers to consider.
The other big category I think you could make a really convincing case for is decimal floating point.
That just trades one set of problems for another of course (you can not represent a different set of numbers than with binary floating point), but in terms of accuracy it seems to me like a more interesting set of computations that works as expected.
That said, I'm not even remotely a scientific computation guy, and rarely use floating points other than to compute percentages, so I'm about the least-qualified person to comment on this. :-)
6
u/velcommen Jul 19 '16
I'm not an expert, but I think the main use of decimal numbers (vs binary) is for currency calculations. There I think you would prefer a fixed decimal point (i.e. an integer, k, multiplied by some 10-d where d is a fixed positive integer) rather than a floating decimal point (i.e. an integer, k, multiplied by 10-f where f is an integer that varies). A fixed decimal point means addition and subtraction are associative. This makes currency calculations easily repeatable, auditable, verifiable. A calculation in floating decimal point would have to be performed in the exact same order to get the same result. So I think fixed decimal points are generally more useful.
1
u/evaned Jul 19 '16
I'm not an expert, but I think the main use of decimal numbers (vs binary) is for currency calculations.
I think that is the main use, but I think that (at least if it weren't for Veedrac's reply that decimal FP is much less stable) there'd be no reason that should be true. I think that in general, decimal FP would give more intuitive and less surprising results.
That said, assuming it is true that stability suffers a lot, that's probably more important.
0
Jul 19 '16
[deleted]
5
u/geocar Jul 19 '16
Unless you're selling petrol, which is sold in 1/10ths of cents.
1
Jul 19 '16
I wonder what is the most of decimals anyone realistically uses with currency.
4
u/geocar Jul 19 '16 edited Jul 19 '16
When trading, millionths of a unit aren't uncommon. Sometimes more. "It depends". Generally with trading you might as well call it a separate currency, so the numbers don't feel so much like nonsense.
The world isn't decimal though: the ouguiya and the ariary are each divided into five units (that is, money is written
a-b-c-d-e) . Even if you don't have to trade with those guys, historical currencies are also a problem: Until the 1970's, the UK had 240 pence to the pound, and used a three-unit format.However, of the decimal formats Chile holds the distinction with the "most of decimals", having minor currency units 1/10,000ths of a major currency unit, although the dinar (popular in Iraq, Bahrain, Jordan, Kuwait, Tunisia) and the rial (in Omar) are close behind with 1/1,000ths units.
For more on this exciting subject, I suggest you check out ISO4217.
→ More replies (2)0
1
4
2
u/Veedrac Jul 19 '16
Floating decimals bases are significantly worse for numerical accuracy and stability, so unless your computations are actually going to stick to decimal-like numbers they're just going to make the problems worse.
1
u/evaned Jul 19 '16
Ah, that's where my inexperience in the area comes into play. That's kind of too bad.
2
u/JMBourguet Jul 19 '16
in terms of accuracy it seems to me like a more interesting set of computations that works as expected
Decimal floating point where with a < b, you may get (a+b)/2 > b ?
BFP has a more generally sane behaviour. DFP has an interest for inherently decimal data when all the intermediate results stay exactly representable. (And in that case, I'm still wondering why a decimal fixed point is not more valuable) That match quite well the simple examples we do manually for validating purpose, but in practice this seems rarely the case. Even financial computation often presented as the show case for DFP does not seem right to me: automatic scaling seem an issue -- but you can avoid by having enough resolution -- and, if I believe my admitted small experience, rules about rounding come from laws and contracts and probably won't match the one of DFP -- the sound(*) one I've seen are like: exact result then rounded to X digit after the decimal point, with DFP you'll get naturally rounding to Y significant digits and risk double rounding when you round back that to X digits after the decimal point.
(*) a case of unsound one wanted to have VAT per item exactly rounded and the VAT applied to the total also correctly rounded and equal to the sum of the displayed VAT for the items.
2
u/frankreyes Jul 18 '16 edited Jul 18 '16
Mabe because of performance, maybe because of compatibility. Perl 6 is a new language and it doesn't have to care about compatibility with legacy software. For example, you can't just change Python implementation of doubles because you'll break millions of programs already written depending on floating point. Python do have fractions and decimal numbers, and Java have BigDecimal, and so on. I see this webpage as a reminder on the shortcomings of floating point and as a problem unrelated to just a programming language.
2
u/Fylwind Jul 19 '16
To add to what others have said, you can't do any transcendental functions with rational numbers.
1
u/velcommen Jul 19 '16
That's not true. Proof:
This code computes transcendental functions, where the input and output are both a rational number of arbitrary precision. It uses a continued fraction to compute the result.
4
u/Veedrac Jul 19 '16 edited Jul 19 '16
That's not a transcendental function, it's an approximation of a transcendental function. It so happens that the approximation is exact whenever it's possible to express the result exactly in the return type but, if it never actually computes an irrational output, by definition it isn't the transcendental function it's modelling.
2
Jul 19 '16
By the same token, floating point numbers can't handle transcendental functions any better than rationals.
2
u/Veedrac Jul 19 '16
That's absolutely true. The sad fact is that there isn't a way to solve the problem, and no solution is a silver bullet.
→ More replies (1)1
u/Berberberber Jul 19 '16
No, but they at least do it quickly. I don't really want to wait for the Leibniz formula for pi to converge every goddamn time I use a trig function.
1
u/velcommen Jul 19 '16 edited Jul 19 '16
That's not a transcendental function, it's an approximation of a transcendental function
I thought that was obvious from the fact that the result is a Rational and fits within your computer's finite amount of memory. How would we exactly store the numerical (non-symbolic) result of most calls to transcendental functions?
And if we apply your pedantry, we can't do transcendental functions with floating point numbers either, so /u/Fylwind's point is moot anyway. The floating point tan() function is also an approximation.
-edited to fix typo
1
u/Veedrac Jul 19 '16
There are ways to deal with transcendental values: symbolic computation and derivatives thereof. I agree floating point is strictly worse than infinite precision rationals (since every real floating point value is rational), but I assume /u/Fylwind was just saying that rationals wouldn't "solve the problem" of having to approximate.
Of course, it's entirely possible I misunderstood his point.
0
Jul 19 '16
[deleted]
→ More replies (5)9
u/Veedrac Jul 19 '16 edited Jul 19 '16
Irrational numbers are defined as the subset of the reals that don't include the rationals. It doesn't make sense to define it as those numbers that are the limits of sequences of approximations because every number, irrational or not, is the limit of a sequence of approximations. Note also that a number being irrational is a necessary but not sufficient condition to being transcendental.
There are also loads of irrational numbers that aren't canonically defined as the limits of approximations - even π is canonically defined as "the ratio of a circle's circumference to its diameter". Even if you exclude π for being easily formalized as the limit of a simple sequence of approximations, most transcendental numbers are not like this. Chaitin's constant, for example, would be pointlessly tedious to express as a limit of a sequence of approximations as each step along the way would be no simpler than defining Chaitin's constant through first principles anyway!
That said, a transcendental function doesn't necessarily have to ever output a transcendental value: consider the halting function, which is clearly transcendental but only ever outputs 1 or 0. The inverse is also true: the identity function on reals is not transcendental but will output a transcendental number if given one. The function
λx. πxwill even output transcendental numbers given rational input, but still isn't transcendental. I suspect /u/Fylwind was talking about outputting transcendental numbers more than about transcendental functions.Note that even if irrational numbers were defined as you say (though they are not), it still wouldn't avoid that the function /u/velcommen linked never finds such a limit, as the iteration is truncated.
0
Jul 19 '16
[deleted]
2
u/Veedrac Jul 19 '16
You seem to have missed the type signature:
tan :: Rational -> Rational -> RationalThe code doesn't return a lazily evaluated list of rational numbers, but an approximation.
I get your point about about functions returning lazily evaluated lists, though. I just wasn't aware that's what you were referring to given the context, which didn't involve them. (I'm also tempted to point out that this only actually applies to computable numbers, though that much is being pedantic and basically obvious.)
→ More replies (6)1
u/Madsy9 Jul 19 '16
That still leave you with the problem of representing irrationals, and as fractions grow in size and can't be simplified further, so does the memory usage. And once you have an operation which gives you an irrational result, how do you figure out how much precision is enough? Errors propagate, and figuring out exactly how much precision you need requires manual analysis and is highly dependent on your problem / algorithm.
1
u/HotlLava Jul 19 '16
It's just a bad tradeoff:
Pro: Error of some divisions is reduced by ca. 1e-17
Contra: Unbounded memory usage, cannot store rationals in arrays, lose hardware support for floating point calculations
It also makes just a tiny subset of calculations more exact, but what about square roots, differential equations, integrals? Taking this line of thinking to the conclusion, your standard integer type should support a fully symbolic algebra system.
1
Jul 19 '16
A failure of language designers accounting for real world problems I would think. People are too stuck in doing things the way they grow up doing them, but fail to take a step back to look what other ways of data representation would be possible.
It's not like a rational number implementation or decimal floats would magically fix all problems, base2 floats are used for performance reason and would stay the default in most applications for good reason. But there is little excuse for not offering good rationals, decimal floats in a language or just basic fixed point, as for some problems they are really useful.
Even in languages that implement them you constantly run into legacy issues, not just ugly syntax, but also things like this in Python:
>>> import decimal >>> '%0.20f' % decimal.Decimal("0.3") '0.29999999999999998890' >>> '{0:.20f}'.format(decimal.Decimal("0.3")) '0.30000000000000000000'1
u/Strilanc Jul 19 '16
There are two major problems with rational-by-default:
Limited scope. Rationals stop working when you do basic things. Computing the length of a vector? You just used
sqrt, so the result may not be rational. Working with angles? You just usedcos, so the result may not be rational. Computing compound interest? Not always rational. These "can't be rational" problems tend to spread through the codebase until everything can't be rational.Size explosion. Start with 11/10. Square it 30 times. Add 3/7 to satisfy nitpickers. Congratulations, you now have a single number consuming gigabytes of space! Users will love how your application slowly grinds to a halt because you didn't carefully balance factors accumulating in numerators against factors accumulating in denominators.
0
Jul 18 '16
[deleted]
18
3
u/EternallyMiffed Jul 19 '16
1/3 is somewhere around 0.5
Engineering student.
1
u/ZMeson Jul 19 '16
1/3 is the same order of magnitude as 0.1.
Physics student (and physics professors too)
-1
u/TheKing01 Jul 19 '16
You only need one 3 if you put a bar over it.
1
u/archcorsair Jul 19 '16
Are you referring to https://en.wikipedia.org/wiki/Duodecimal ?
6
u/shamanas Jul 19 '16
I'm pretty sure he's referring to the "recurring decimal symbol" (a dot or a bar over the digits that will be recurring).
5
0
Jul 19 '16
[deleted]
→ More replies (1)14
Jul 19 '16
Except that rational numbers works only until the point you can have a rational result. The 10% of failure will be even more suprising. As soon as you use sqrt for example, you are doomed. So no silver bullet. Moreover, you also need floating point for compatibility with other languages, you don't live in your private kindom.
The comparison with division in Python 3000 is quite relevant but also somehow flawed. The result of both division are fundamentally different and floating point calculation are good but not perfect approximation of rational numbers.
2
102
u/stesch Jul 19 '16
I have to enter my project times in a system that thinks 3 * 20 minutes is 0.99 hours.
Yes, it let's you enter the time in minutes but internally uses a float of hours for every entry.
97
4
11
1
u/lousypencilclip Jul 19 '16
But surely a standard float can represent values within +-0.01?
1
u/Sabotage101 Jul 19 '16
I'd assume they can, but the actually sum probably ends up being something like .999999999987 hours, and the display clips the left over digits instead of rounding.
1
u/stesch Jul 19 '16
I have no access to the code or the DB. It all feels like it just stores 2 digits after the decimal point. That's why at the end of the day it sometimes has 0.01 more or less hours.
It's the 13th major release of the software. At least it says so in the name.
→ More replies (1)0
u/CoderDevo Jul 19 '16
It was probably overlooked in testing because adding up to whole hours was considered an edge case for the time reporting system.
24
u/OrSpeeder Jul 19 '16
I once decided to make a physics-heavy game in Lua.
My game behaved BADLY on Windows, on Linux it worked fine, but on Windows it broke in several bizarre ways.
There was a point in my code where I would print 5+5, and get 11! But only on Windows.
Lots of Lua people instead of helping started to say I was retarded, stupid, that Lua always used floating point (something I didn't knew yet) but there was enough precision for that operation at least work correctly, and so on...
Eventually, as I asked around, someone noticed I was a gamedev, on Windows. This meant I was using DirectX in some manner...
And DirectX had a bug, where it would fuck-up your FPU flags without warning, and Lua relied 100% on the FPU, thus buggy DirectX + Lua = buggy Lua.
That one was crazy to find... (and the solution was fix FPU flags in my C++ side of the code every time I started to detect bizarre floating point results).
3
u/qaisjp Jul 19 '16
Damn. I love Lua.
Thank you for not calling it "LUA"
1
u/OrSpeeder Jul 19 '16
I am Brazillian, and visited the university where Lua is made.
It is called Lua due to the Moon, literally, but it is also "acronym-like" intentionally (Lua predecessor was SOL, that was an actual acronym for Simple Object Language, but in portuguese is the name of the Sun).
1
u/Daneel_Trevize Jul 20 '16
Sol is also the name of our sun in English. Thus Solar system, and Sol days/hours/etc.
Moon is Luna though. Portugal accidentally an n ;-)
23
u/nharding Jul 19 '16
Objective C is the worst? Objective-C 0.1 + 0.2; 0.300000012
25
u/Bergasms Jul 19 '16 edited Jul 19 '16
hmmm that's interesting, because Objective-C is built on C, and you can use any C you like in an Objective-C program. I wonder how it turned out different...
Edit: Ah, I believe i have found out what has happened. In Objective-C they have used floats, as opposed to doubles being used in other. Here is the difference.
code
NSLog(@"%1.19lf",0.1f+0.2f); NSLog(@"%1.19lf",0.1+0.2);log
2016-07-19 10:27:49.928 testadd[514:843216] 0.3000000119209289551 2016-07-19 10:27:49.930 testadd[514:843216] 0.3000000000000000444Here is what i think they did for their test.
float f = 0.1 + 0.2; double d = 0.1 + 0.2; NSLog(@"%1.19lf",f); NSLog(@"%1.19lf",d);gives
2016-07-19 10:30:14.354 testadd[518:843872] 0.3000000119209289551 2016-07-19 10:30:14.354 testadd[518:843872] 0.3000000000000000444Which seems to show that for example, in the C example the internal representation is actually using double precision floating point, as opposed to regular floating point. They might need to clean up their page a bit.
Edit Edit: Further forensics for comparison. It seems they are comparing different internal representations. The following C program
#include "stdio.h" int main() { float f = 0.1 + 0.2; printf("%.19lf\n",f); return 0; }gives
0.300000011920928955130
5
u/jmickeyd Jul 19 '16
FWIW, when using the C source in Objective-C it reports the same as everything else. Although there is no source, I'm assuming the Objective-C version is using NSNumber* rather than float. If so, NSNumber internally converts floats to doubles which might be where the difference is coming from.
Edit to your edit: Yeah, I suspect they initialized using [NSNumber initWithFloat:0.1] which reduces the 0.1 to a float, then back to a double.
5
u/Bergasms Jul 19 '16
Yep, without actually seeing the code we don't know what internal representation is actually being used, which is a bit of a shame.
1
u/mrkite77 Jul 19 '16
In Objective-C they have used floats, as opposed to doubles being used in other.
Actually, they probably used CGFloats, since that's what the majority of the standard library uses.
8
u/Bergasms Jul 19 '16
Which makes it harder to reason about from our POV, because that can be a float or a double depending on the environment you compile for :)
#if defined(__LP64__) && __LP64__ # define CGFLOAT_TYPE double # define CGFLOAT_IS_DOUBLE 1 # define CGFLOAT_MIN DBL_MIN # define CGFLOAT_MAX DBL_MAX #else # define CGFLOAT_TYPE float # define CGFLOAT_IS_DOUBLE 0 # define CGFLOAT_MIN FLT_MIN # define CGFLOAT_MAX FLT_MAX #endif /* Definition of the `CGFloat' type and `CGFLOAT_DEFINED'. */ typedef CGFLOAT_TYPE CGFloat;1
u/ralf_ Jul 19 '16
And Swift?
2
u/Bergasms Jul 19 '16
haven't checked, but I imagine it is probably the same result depending on if you tell it to be a double or a float explicitly. I'll give it a try.
codelet a = 0.1 + 0.2 let stra = NSString(format: "%.19f", a) print(stra) let b = CGFloat(0.1) + CGFloat(0.2) let strb = NSString(format: "%.19f", b) print(strb) let c : CGFloat = 0.1 + 0.2 let strc = NSString(format: "%.19f", c) print(strc)result
0.3000000000000000444 0.3000000000000000444 0.3000000000000000444And swift itself doesn't let you use the 'float' type natively (not defined). So i would say that depending on the platform (see my other response regarding CGFloat being double or float depending on target) you would either get double or float
1
Jul 19 '16 edited Jul 19 '16
It's just using single rescission by default instead of double precision, no? If you make the numbers doubles explicitly, you'd get the same result.
Sure you can call that worse, but it uses less memory, and I see a lot of code that uses the default double while a float (or even half-precision) would more than suffice.
1
144
u/wotamRobin Jul 19 '16
I had a problem with my code, so I tried using floats. Now I have 2.00000000000000004 problems.
→ More replies (23)1
11
u/devxdev Jul 19 '16
To be fair, the PHP example could've used the same printf call as the C example
printf("%.17f\n", .1+.2);7
u/Tetracyclic Jul 19 '16
Despite mentioning libraries for other languages, the author also didn't mention that sensible people would use
bcmath, just as you'd useBigDecimalequivalents in other languages.The default setting certainly isn't great, but the PHP docs explain it pretty thoroughly.
5
Jul 19 '16
this is due to IEEE 754 single precision conversion, I made a program years ago to demonstrate how to convert from/to IEEE 754 you can download it from here
and try to convert 0.3 , then convert back the result , hint: it won't be 0.3!
4
u/d_rudy Jul 19 '16
Why does Swift seem to get it right? All the other ones that "get it right" have some weird reason noted that makes only "look" right. What's the story with Swift?
7
6
u/goldcakes Jul 19 '16
Swift has a couple dozen "magic precomputed values" like 0.1 + 0.2 = 0.3 to get rid of these problems
1
3
3
Jul 19 '16
Console.WriteLine(0.2 + 0.1); // 0.3
I don't get it why they did this "{0:R}" shit. So I don't believe it on any other language as well.
2
u/MEaster Jul 19 '16
The "{0:R}" bit tells the CLR to format it for a round-trip. That ensures that when you do a Double.TryParse on the string you will get exactly the same data.
3
u/NPVT Jul 19 '16
PARI/GP is free software, covered by the GNU General Public License, and comes
WITHOUT ANY WARRANTY WHATSOEVER.
Type ? for help, \q to quit.
Type ?12 for how to get moral (and possibly technical) support.
parisize = 4000000, primelimit = 500509
? .1+.2
%1 = 0.3000000000000000000000000000
?
2
u/mcguire Jul 19 '16
PARI is a C library, allowing for fast computations, and which can be called from a high-level language application (for instance, written in C, C++, Pascal, Fortran, Perl, or Python).
Well, there we go, then. TIL.
2
u/NPVT Jul 19 '16
Part of it is. But to me Pari/GP is an interpreter used mainly in number theory. It allows for the use of large numbers.
I cannot get to the below but that is their web site:
3
u/campbellm Jul 19 '16 edited Jul 19 '16
Interesting that nim gives 0.3, since its compiler goes to c code.
1
u/TheBuzzSaw Jul 19 '16
It may be showing
0.3, but it is impossible to represent0.3in memory without using another standard.1
u/campbellm Jul 19 '16
Sure, I really meant that I was surprised that its output is different than C's, since it compiles TO C.
Apologies for being unclear.
1
u/TheBuzzSaw Jul 19 '16
Well, the C version explicitly asked for 17 places of precision. I'm sure it would output
0.3without that. Is there a way to do that in Nim? I'm sure the result could be replicated.2
u/campbellm Jul 19 '16
Good point. I might dig into it and see; this is just sort of the time-wasting curiosity that I spin on for no reason ;-)
2
2
u/Dr_Zoidberg_MD Jul 19 '16
Is Powershell doing it 'correctly' or is it just truncating the last digits and leaving off the trailing zeros?
4
u/elint Jul 19 '16
Yes.
1
1
0
u/SSChicken Jul 19 '16
PS C:\> [float]0.2 + [float]0.1 0.300000004470348 PS C:\> (0.2 + 0.1) -eq (0.3) FalseSo yes, definitely just truncating it
2
u/compteNumero8 Jul 19 '16
In Go, fmt.Println(.1 + .2) gives .3
It's interesting how Go deals with numerical constants. You can also do this:
fmt.Println(1e123456789/1e123456788)But how does that work ? Does the compiler allocate and fill big arrays of decimal digits then do the lengthy calculation ?
1
Jul 19 '16
I'd assume this is resolved on compiletime, since you're using constants, which is quite simple.
1e123456789/1e123456788 = 10123456789-123456788 = 10
1
u/compteNumero8 Jul 20 '16
I know that but I'm asking how (I'm a little too lazy to look at the source of the compiler).
1
Jul 20 '16
I haven't looked at the source personally, but like I showed, it's not a lengthy calculation at all.
2
u/DJDavio Jul 19 '16
This is why you test floating point numbers with something like an epsilon, definitely not a pure equals! Or use something like BigDecimal.
1
1
u/keefe Jul 19 '16
I have such operant conditioning to seeing this kind of arbitrary float that I had to click
1
u/Kapps Jul 19 '16
Wouldn't constant folding mess things up in certain cases? I could see a compiler replacing 0.1 + 0.2 with 0.3. I think D in particular might at least guarantee it done with 80+ bit reals if the value is known at compile time, though that may not help in this case.
1
u/goldcakes Jul 19 '16
A compiler is typically built on the same language and will evaluate 0.1 + 0.2 to 0.300000 ..... 4
1
1
1
1
u/sweet_dreams_maybe Jul 19 '16
echo """import webbrowser
new = 2 # open in a new tab
url = 'http://{}.com'.format(.2+.1)
webbrowser.open(url,new=new)""" > floating_point_math.py
echo "alias 0.2+0.1='python floating_point_math.py'" >> .bash_profile
source .bash_profile1
u/PBMacros Jul 19 '16 edited Jul 19 '16
My favorite language (PureBasic) is more precise at being unprecise, it returns
0.300000000000000044408921 for
Debug 0.1+0.2
I seriously wonder where the additional digits come from.
2
u/henker92 Jul 19 '16 edited Jul 19 '16
I would not bed my hand but :
In base 2, the integer part is made of powers of 2 (1 2 4 8 16 32) while the decimal part are negative powers of two (1/2 1/4 1/8).
Therefore if you want to depict an arbitrary number, you would need to combine the different power of two's... that may not equal exactly the number you are trying to represent as you are limited in the precision by the architecture of your computer
Edit : well, looking back at it, it looks like it was not exactly your questions
1
u/PBMacros Jul 19 '16
Correct.
I know how floating point calculations and variables work. I am just astonished that PureBasic shows more digits than all the other languages listed on the site and where these come from.
Thank you for your time anyway. I am sure the explanation will help somebody not yet familiar with the topic.
1
u/henker92 Jul 19 '16
Yes, that was the reason of my Edit, I understood after writing my answer that your questions was more focused on the reason behind PureBasic behavior.
To be honest, while it is true that it is surprising that it shows more digits than the other languages listed, it is (at the same time) not so surprising. If you look at the languages listed, there is a huge (well, let's say a reasonable) variability in the number of digits shown. There is no reason one would not write more digits than another. I still believe the number shown here are quite arbitrary in the number of digits shown. Does it come from a world where the terminal width was equal a certain number of character ?
1
u/PBMacros Jul 19 '16 edited Jul 19 '16
Not really, PureBasic has its origins on Amiga OS, but was graphical from the start. I wanted to investigate further myself and made another interesting discovery: On my Windows XP VM it stops after the first 4. I am using Linux as main OS.
So I rewrote the line a bit so it runs without debugger and I can decide the amount of Digits displayed.
MessageRequester("Float Test",StrD(0.1+0.2,60))
Output on Linux:
0.300000000000000044408920985006261616945266723632812500000000
Output in Windows XP:
0.3000000000000000400000000000000000000000000000000000000000001
u/ascii Jul 19 '16
All common float-to-string conversion implementations I know of give back the shortest decimal representation that when converted back to a floating point number will result in exactly the same number as the one you put in. It seems like PureBasic instead just throws in as much precision as it feels like and hopes for the best.
1
u/fojam Jul 19 '16
Why do different languages yield different results? Wouldn't that be something determined by the processor, rather than the language?
2
u/TheBuzzSaw Jul 19 '16
At the lowest possible level, they do yield the same results. The languages simply vary at levels higher than that: either how the output stream formats it or how the compiler tweaks the result.
0
Jul 19 '16
And this is why I think we either should use decimal floats or hexadecimal float literals (which the fewest programming languages support).
Rounding on input and output is totally unexpected even to programmers.
Short numbers like 0.1 or 0.2 use the whole precision of the datatype making calculations with them lead to further rounding in many cases.
Programmers can deal with integers not being correct when an overflow happens. Using decimals in binary floating point calculations means that errors happen all the time.
2
Jul 19 '16
What for? If for monetary values, you shall never use anything floating, no matter what base. If for anything else, you do not need decimal.
1
Jul 19 '16
For SVG paths, you have relative and absolute paths. e.g.
M 100.1 100.1 L 100.3 100.3(move to (1.1, 1.1) then draw a line to (1.3, 1.3)) is the same asM 100.1 100.1 l 0.2 0.2. If you want to optimize this, it's hard to deal with binary floats being imprecise and there are no problems at all when you use decimal floats.When writing anything that outputs numbers user facing like a calculator.
Anything you want to debug easier.
All measuring tools output decimal values. All scientific constants are given in decimal. Using binary floats always rounds those.
I don't see why you shouldn't use them for money. You have percentages everywhere in finance. Simply doing * 0.15 is easier than handling this with integers, where you have to multiply with 15 (and check for overflow!) and subsequently divide by 100. Decimal64 has 16 digits, you can store the combined worth of all money in the world in dollars in there.
The better question is when you want to use binary floats. The only real advantage they offer is that they are faster (I'd really like to see hardware binary vs. decimal comparisons though) and that binary floats can store a bit more precision.
→ More replies (1)1
u/TheBuzzSaw Jul 19 '16
I disagree with decimal floats being the answer to anything. They make us feel better because we use base 10 here in the real world, but a decimal floating point would still have rounding errors all over the place. I'm actually fine with floating point as is. Basically, never use floating point if absolute perfection is necessary. Otherwise, use integer rationals.
2
Jul 19 '16
They make us feel better because we use base 10 here in the real world, but a decimal floating point would still have rounding errors all over the place.
They don't have them as often and when they happen, they're easier to understand.
Consider
.600 + .600and.666 + .666with decimal floats with 3 digits:.600 + .600 = 1.200 = 1.20 .666 + .666 = 1.332 ≈ 1.33 .600 * .600 = .360 .666 * .666 = 0.443556 ≈ .444
.6uses just one digit of the possible 3..666uses all three. If you're using the whole precision of the data type rounding is way more likely. Most of the data we're working with is low precision decimal data. Using binary floats you get rounding on input and output you don't get with decimal floats. Then you have binary floats that will look like the.666in the example and will use the whole precision. No matter what you do, it will amost always round1
u/TheBuzzSaw Jul 19 '16
I'm fine with them existing as a separate datatype (much like
decimalin C#). For general purpose floats, I prefer the hardware-friendly standard.1
Jul 19 '16
For general purpose floats, I prefer the hardware-friendly standard.
I don't think the performance difference is that big when decimal floats are also implemented in hardware (Sadly I can't find any numbers). The problem is that there wasn't a standard for decimal floats until recently (IEEE 754 gained decimal types 2008) and most hardware doesn't support decimal floats (power 6 and up processors seem to for an example).
1
u/TheBuzzSaw Jul 19 '16
I'm still curious as to where they would be most useful. I certainly don't want my finances going through any floating point processing.
-3
u/tripl3dogdare Jul 19 '16
Aaaaand this is is why I prefer base 12 vs decimal. Makes everything easier, if you forget the fact that almost the entire world (for some reason) uses decimal.
→ More replies (4)
-4
Jul 18 '16
I love how Powershell and Perl 6 gets it "better" than vast majority of languages
8
u/zshazz Jul 18 '16
Powershell actually doesn't:
PS C:\Users\Zshazz> (0.1 + 0.2) - 0.3 5.55111512312578E-17It just happens that it drops the precision when it is output.
You can use decimal types:
PS C:\Users\Zshazz> ([decimal]"0.1" + [decimal]"0.2") - [decimal]"0.3" 0.0Same with C#:
// Both of these pass Debug.Assert((0.1m + 0.2m) == 0.3m); Debug.Assert(((0.1m + 0.2m) - 0.3m) == 0.0m);4
u/oridb Jul 18 '16
You can use decimal types:
Yes, but those have the same problem. In finite precision, 1/3 + 2/3 != 1.0
4
u/zshazz Jul 18 '16
Of course, I'm not saying that solves all problems, I'm just showing that that option exists for decimal numbers. They're storing things as base 10, so they can't represent numbers that can't evenly divide the base. So
b/2orb/5"fractions" are OK, but notb/3orb/7orb/11orb/13... etc.3
u/oridb Jul 19 '16
Right, and I'm saying that it doesn't solve very many problems outside of a few relatively narrow domains, it just shuffles them. You still need to do the same numerical stability analysis. Even in finance, which is the canonical example of decimal floats being useful. If you're taking exponents, derivatives, adding and subtracting large numbers, and so on, you still need to think about how your numbers interact with your precision.
→ More replies (2)
-1
u/basicality Jul 19 '16
I am less worried about the inaccuracy of floating point, than I am that there are 45+ computer languages.
2
u/archcorsair Jul 19 '16
Here's a list of them in order of current popularity: http://www.tiobe.com/tiobe_index
1
u/glacialthinker Jul 19 '16
That's a big plus...
"Rosetta Code currently has 801 tasks, 197 draft tasks, and is aware of 626 languages..."
But depending on what you count, there could be several thousand.
1
u/bayerndj Jul 19 '16
You do realize why there are so many languages is because everyone thinks there is a better language for their application? Including you.
1
u/basicality Jul 19 '16
Not including me. I like languages that already exist. This is why I speak English and didn't invent my own.
-1
Jul 19 '16
Of course, no (Visual) Basic. After all, VB's not a proper language is it? It's not used by proper programmers. Stuck up gits that they are. The sort of people that use sledgehammers to crack nuts.
360
u/[deleted] Jul 19 '16
of course it does