为什么在非整数值上使用模数会失去浮点精度? [英] Why does using modulo on non-integer values lose floating-point precision?

查看:149
本文介绍了为什么在非整数值上使用模数会失去浮点精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么我在使用此代码时会失去精确度:

I am wondering why I am losing precision when using this code :

double x = 12.0456;    // or float : same result
System.out.println(x); // outputs 12.0456 obviously
x %= 1;                // should now be equal to 0.0456 right?
System.out.println(x); // outputs 0.04560000000000031 or 0.045599937 when using float

12.0456模数1应该等于0.0456对吗?
但是它显示了一个稍微不同的值,为什么我会不断丢失精度?我的意思是代码应该正好减去1,直到值小于1.

12.0456 modulo 1 should equal 0.0456 right? But it shows a slightly different value, why do I keep losing precision? I mean the code should substract exactly 1 until the value is less than 1.

然而,我找到了一种获得正确值的方法:

However, I found out a way to get the correct value :

double x = 12.0456;
System.out.println(x);
x %= 1;
System.out.println((float)x); //outputs 0.0456 exactly

这种方式很完美,但你们有更好的解决方案吗?

This way works perfectly, but do you guys have a better solution?

我不关心我应该使用哪种浮点类型,我只想找到一种干净的方法来获得正确的值!我不知道喜欢必须将值转换为double然后转换为float。

I don't care which floating point type I should use, I just want to find a clean way to get the correct value! I don't like having to convert the value to a double and then to a float.

推荐答案

Float和double是不精确的 - 他们有一个用于表示值的有限位数。

Float and double are imprecise - they have a finite amount of bits to represent a value.

因为人类使用基数10,而计算机使用基数2,所以对我们来说看起来简单的数字无法准确表示作为float / double,特别是由于CPU执行它们的计算结果。

Because humans use base 10, and computers use base 2, numbers that appear "simple" to us can be impossible to represent accurately as a float/double, especially the results of computations due to way CPUs execute them.

这篇关于为什么在非整数值上使用模数会失去浮点精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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