在这种情况下,我应该如何对浮子取整? [英] How should I round a float in this case?

查看:117
本文介绍了在这种情况下,我应该如何对浮子取整?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于相同的浮点数可能具有多种表示形式,所以我的代码存在问题. 例如,这些数字被认为是相同的:

I'm having issues in my code due to the multiple representations that a same float number can have. For instance, these number are considered to be the same:

  • 0.0299999400
  • 0.0300000000

我不太关心精度,我需要计算这些数字的 CRC ,它们应该是相同的,所以我的方法是使用以下代码:

I don't care much for a big precision, I need to calculate CRC of those numbers and they should be the same, so my approach was to use this code:

private static float Rounding(float v, float p)
{
    return Mathf.Round (v * p) / p; 
}

p 是我的精确度.

这似乎工作得很好,但是在这种情况下,如果我使用 p = 1e7 ,则第一个数字乘法将导致 299999.4 并四舍五入为 299999 ,变为 0.0299999 ,而 0.03 将保留为 0.03 .那是我的问题.

That seems to be working well, but in that case, if I used p = 1e7, the first number multiplication would result in 299999.4 and rounded to 299999, becoming 0.0299999, while 0.03 would remain 0.03. That's my problem.

我在做正确的事情吗?也许答案是我不能使用这么大的 p ,但是我不知道浮点数如何工作,所以我不知道 p 的大小在任何情况下都可以工作.

Am I doing the right thing? Maybe the answer is that I can't use a p this big, but I don't know how floats work, so I don't know the size of p to work in all situations.

但是,我知道我的浮点值位于一个不如浮点范围大的范围内(±1.5e−45到±3.4e38).我的意思是,如果我知道我的浮动范围是[-100; +100],我可以假设它将有足够的十进制数字来表示 p 3 .是吗?

However, I know that my float values resides in a range that is not as big as the float range (±1.5e−45 to ±3.4e38). What I mean is, if I know that my floats range is [-100; +100], I can assume that it will have enough decimal digits for p to be 3. Is that right?

还有另一种方法吗?

推荐答案

您应将数字转换为 decimal ,然后回合达到所需的精度. decimals的准确性与准确性一样,因此您可以例如将它们转换为字符串和哈希,而不会遇到任何此类问题.

You should convert the numbers to decimal and then round to the required precision. decimals are as accurate as they are precise, so you can then e.g. convert them to string and hash without having any such problems.

这篇关于在这种情况下,我应该如何对浮子取整?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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