在师小数舍入误差(C#) [英] Decimal rounding errors upon division (C#)

查看:126
本文介绍了在师小数舍入误差(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经基本上四个数字(如100,200,300,400),我需要计算的概率为100 /(100 + 200 + 300 + 400),200 /(100 + 200 + 300 + 400) ,等等。

I have basically four numbers (say 100, 200, 300, 400), and I need to calculate the probability as 100/(100+200+300+400), 200/(100+200+300+400), and so on.

当我使用十进制数据类型来存储这些概率,他们没有达人,由于圆的问题。什么是过去最好的办法未做概率太不精确?基本上我做这个计算很多很多次,所以我不希望有改变所有的部门变成Math.Round东西。 :|

When I use the decimal data type to store these probabilities, they don't up to one due to round issues. What's the best way to past this without making the probabilities too inaccurate? Basically I do this calculation many many times, so I don't want to have to change all the divisions into Math.Round stuff. :|

推荐答案

解决的办法很简单:如果你那样做的话不要做伤害了

The solution is straightforward: if it hurts when you do that then don't do that.

如果你的理性的概率,也就是全是数字的比例,并且希望他们能够加入到只有一个,那概率的不将其转换为十进制或双放在首位的。 。使用任意精度的理性类型来表示你的任意精度有理数

If you have rational probabilities, that is, probabilities that are ratios of whole numbers, and you want them to add to exactly one, then don't convert them to decimal or double in the first place. Use an arbitrary-precision rational type to represent your arbitrary precision rationals.

有是包含在Microsoft求解基金会的任意精度的理智型;你可以下载并使用它。或者说,它很容易被简单地使有两个BigInteger的分子和分母,然后写上你所需要的运营商实现一个不变的结构来写自己的。

There's an arbitrary-precision rational type included with Microsoft Solver Foundation; you could download and use that. Or, it is easy to write your own by simply making an immutable struct that has two BigIntegers for the numerator and denominator, and then write implementations of the operators you need.

这篇关于在师小数舍入误差(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆