MySQL浮点舍入错误 [英] MySQL floating point rounding error

查看:81
本文介绍了MySQL浮点舍入错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在内部,右边的浮点表示形式怎么回事会变成假?

Internally, what is going on with the floating point representation on the right to get false?

mysql> SELECT 3.1415 + 0.9585 = 4.1, 3.1415E0 + 0.9585E0 = 4.1E0;
+-----------------------+-----------------------------+
| 3.1415 + 0.9585 = 4.1 | 3.1415E0 + 0.9585E0 = 4.1E0 |
+-----------------------+-----------------------------+
|                     1 |                           0 |
+-----------------------+-----------------------------+

修改 结论:不要将Float或Double用于精度数学.使用十进制.

edit Conclusion: Don't use Float or Double for precision math. Use Decimal.

推荐答案

首先,永远不要使用浮点运算符=,因为您根本无法预测是否不会发生舍入错误.始终使用<或>,取决于您要实现的目标.

First of all, you should never use = with floating points, as you simply cannot predict if no rounding errors occur. Always use < or >, dependent on what you want to achieve.

第二:任何一个公式都没有错.在内部,两个变体都在其变量中编码为最接近的可能二进制表示形式,这与您设置的值略有不同.

Second: Nothing is wrong with either formula. Internally, both variants get encoded in their variables to the nearest possible binary representation, which slightly differs from the value you set.

小数点前的一位数字是标准的,因此使用以下所有数字.在右侧,您专门定义了逗号的出现位置,从而在变量的二进制表示形式的末尾浪费"了某个部分-这会导致舍入错误(在这种情况下).

One digit before the decimal point is standard, so all following digits are used. On the right side, you specifically define where the comma occurs, thus "wasting" a certain part at the end of the binary representation of your variable - which leads to rounding errors (in this specific case).

这篇关于MySQL浮点舍入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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