3 ms·
So I have a question. For those that arrive at the right answer, is it by mathematical correctness in the implementation or by rounding down? i.e. Which are r
by headmelted 11y ago
So I have a question.
For those that arrive at the right answer, is it by mathematical correctness in the implementation or by rounding down?
i.e. Which are right and which are flukey in their wrongness?
Under any other circumstance I wouldn't care about this pointless detail, but seeing as how this is the top post on the front page, I'd like an excruciatingly detailed investigation please.
Don't make me not get round to doing it myself, sir.
- Joeri 11y agoIn PHP's case, it converts the value to a printable (string) representation, and in so doing rounds off to a precision of 14 digits. http://lxr.php.net/xref/PHP_5_4/Zend/zend_operators.c#2142 http://lxr.php.net/xref/PHP_5_4/Zend/zend_operators.c#2142 The "mathematically" correct answer is 0.30000000000000004 according to the IEEE-754 spec.
- lsaferite 11y agoIf you want PHP to print it like the other languages you have to set the output precision high enough. The default, as you mentioned, is 14 but if you set it to 17 then you get the 'correct' output. https://3v4l.org/TRcJB https://3v4l.org/TRcJB http://php.net/manual/en/ini.core.php#ini.precision http://php.net/manual/en/ini.core.php#ini.precision
- McGlockenshire 11y agoAnother option is to use printf, as like other languages it can take a precision argument. printf('%.17f', 0.1 + 0.2); // 0.30000000000000004
- brlewis 11y agoScheme and Common Lisp arrive at the right answer to (+ 1/10 2/10) by correctness. They have internal representations for rational numbers.
- Someone 11y agoRead http://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf http://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/pr... and, if you still need more info, a few of the earlier papers it references. All of them may be correct as typically, multiple 'answers' can be correct. One could argue that given a number, one should print the shortest string that round-trips to that number, but that may mean that one prints "0.3" while the 'real' value is closer to 0.30000000000000004 or 0.29999999999999998 (a representation that one of the algorithms in the above paper gives) or possibly even equal to it. Also, some of them may be incorrect for backwards compatibility reasons. In the eyes of some, that makes them correct again. And don't get round to not doing it yourself :-)