小数精度

编程入门 行业动态 更新时间:2024-10-22 03:06:07
本文介绍了小数精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用十进制类型进行高精度计算(货币).

I use the decimal type for high precise calculation (monetary).

但是我今天遇到了这个简单的部门:

But I came across this simple division today:

1//(1/37)应该会再次导致37

1 / (1 / 37) which should result in 37 again

www.wolframalpha/input/?i = 1%2F +%281%2F37%29

但是C#给了我: 37.000000000000000000000000037M

我尝试了这两种方法: 1m/(1m/37m); 和 Decimal.Divide(1,Decimal.Divide(1,37))

I tried both these: 1m/(1m/37m); and Decimal.Divide(1, Decimal.Divide(1, 37))

,但两者产生相同的结果.行为如何解释?

but both yield the same results. How is the behaviour explainable?

推荐答案

Decimal 将值存储为十进制浮点数,但精度有限.1/37的结果未正确存储,因为它存储为0.027027027027027027027027027M.真实数字的组027以十进制表示形式无限期地前进.因此,您无法获得每个可能数字的精确数字(以十进制表示).

Decimal stores the value as decimal floating point with only limited precision. The result of 1 / 37 is not precicely stored, as it's stored as 0.027027027027027027027027027M. The true number has the group 027 going indefinitely in decimal representation. For that reason, you cannot get the precise numbers in decimal representation for every possible number.

如果在同一计算中使用 Double ,则最终结果在这种情况下是正确的(但这并不意味着它将总是更好).

If you use Double in the same calculation, the end result is correct in this case (but it does not mean it will always be better).

关于该主题的一个很好的答案是在这里: .NET中小数,浮点数和双精度之间的区别?

A good answer on that topic is here: Difference between decimal, float and double in .NET?

更多推荐

小数精度

本文发布于:2023-11-23 01:29:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619620.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:小数   精度

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!