TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Subtracting large floating point numbers in different languages

35 点作者 wamatt超过 8 年前

10 条评论

kovrik超过 8 年前
Isn&#x27;t it an expected behaviour (at least for programmers) because of IEEE 754?<p>For example, in Racket this also gives 2.0, but if you are using exact numbers (#e), then it gives exact and correct answer 1.0.<p>Same for Java (and any other language): if you are using Float&#x2F;Double numbers, then you are loosing precision. Use BigDecimal (or something similar for other languages) if you want exact calculations.
评论 #12899793 未加载
评论 #12897211 未加载
评论 #12897308 未加载
ubernostrum超过 8 年前
Alternate title: &quot;How to get IEEE 754 right&quot;.
评论 #12897317 未加载
Lazare超过 8 年前
Kind confused what the point is. Is this a complaint that most languages use IEEE 754 for non-integer numbers and he thinks they shouldn&#x27;t, or a veiled dig about how many programmers don&#x27;t know this, or...?<p>The color coding of results suggests the author thinks that 2 is wrong and 1 is right, but he&#x27;s going out of his way to specify floating point numbers, and when subtracting those two floating point numbers the correct answer is 1 and NOT 2.<p>Eg, Ruby thinks 9999999999999999.0 - 9999999999999998.0 = 2, but 9999999999999999 - 9999999999999998 = 1. Which is...correct. Right? Unless you don&#x27;t think IEE 754 should be the default?<p>I feel like the author is trying to make a clever point, but if so, I&#x27;m not getting it.
ruricolist超过 8 年前
Note that the Common Lisp example could be abbreviated to:<p>(- 9999999999999999.0l0 9999999999999998.0l0)<p>However, this will only work (either way) in Lisps where long floats are arbitrary precision, like CLISP. In most Lisps (e.g. SBCL, CCL), long floats are just double floats.
lightlyused超过 8 年前
For java: BigDecimal b1 = new BigDecimal(&quot;9999999999999999.0&quot;);<p><pre><code> BigDecimal b2 = new BigDecimal(&quot;9999999999999998.0&quot;); System.out.println(b1.subtract(b2));</code></pre> prints 1.0
评论 #12897190 未加载
aftbit超过 8 年前
How does Google get 0 out of that? Both my high school math teacher and IEEE 754 think that&#x27;s wrong.
评论 #12899839 未加载
评论 #12899309 未加载
ivan_ah超过 8 年前
SymPy, being Python, gets it wrong... but if you use S = sympify to transform the long numbers into SymPy objects it works:<p><pre><code> S(&#x27;9999999999999999.0&#x27;) - S(&#x27;9999999999999998.0&#x27;) 1.0</code></pre>
评论 #12897511 未加载
rurban超过 8 年前
The perl5 solution is<p><pre><code> perl -Mbignum -e &#x27;print 9999999999999999.0-9999999999999998.0;print &quot;\n&quot;;&#x27; 1</code></pre>
oulu2006超过 8 年前
MacOS search bar gives the correct result 1.<p>Because it evaluates the expression using the Calculator App.
CalChris超过 8 年前
Wolfram Alpha gives 1. Bing gives 1.
评论 #12897821 未加载