Python浮点算术基础知识 [英] Python floating point arithemetic basics

查看:85
本文介绍了Python浮点算术基础知识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如预期的那样,由于其有限的精度,Python的浮点乘法不能在加法上分配:

As expected because of its finite precision, Python's floating point multiplication is not distributive over addition:

In [10]: 200 * 0.1 + 200 * 0.2
Out[10]: 60.0

In [11]: 200 * (0.1 + 0.2)
Out[11]: 60.00000000000001

加法不具有关联性:

In [12]: 1e14 + (48.18 + 18.26)
Out[12]: 100000000000066.44

In [13]: (1e14 + 48.18) + 18.26
Out[13]: 100000000000066.45

但是加法是可交换的吗?乘法?

But is addition commutative? multiplication?

推荐答案

是的,加法和乘法是可交换的(当结果为NaN时例外,但这是因为NaN!= NaN.在这种情况下,加法和乘法会产生同样的结果,只是这个结果不等于本身.

Yes, addition and multiplication are commutative (with the exception of when the result is NaN, but that's because NaN != NaN. In that case addition and multiplication produce the same result, it's just that this result is not equal to itself).

有限浮点值的加法和乘法都被定义为最接近相应运算的数学结果的浮点值. 即分别是rn(a + b)和rn(a * b).

Both addition and multiplication of finite floating-point values are defined as the floating-point value nearest to the mathematical result of the respective operation. That is, respectively, rn(a + b) and rn(a * b).

这些定义是可交换的,因为a + b = rn(a + b)= rn(b + a)= b + a(对于乘法也类似).

These definitions are commutative because a + b = rn(a + b) = rn (b + a) = b + a (and similarly for multiplication).

这篇关于Python浮点算术基础知识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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