找回密码
 快速注册
搜索
查看: 20|回复: 1

[Floating point arithmetic] Machine epsilon (浮点数机器精度)

[复制链接]

3149

主题

8386

回帖

6万

积分

$\style{scale:11;fill:#eff}꩜$

积分
65391
QQ

显示全部楼层

hbghlyj 发表于 2022-8-3 07:24 |阅读模式


Wikipedia
def machineEpsilon(func=float):
    machine_epsilon = func(1)
    while func(1)+machine_epsilon != func(1):
        machine_epsilon_last = machine_epsilon
        machine_epsilon = func(machine_epsilon) / func(2)
    return machine_epsilon_last
print(machineEpsilon())
Output:
2.22044604925e-16

epsilon.py (same as above method)
# Start with a value that's way too big.
epsilon = 1.0

# Keep halving it until it gets too small.
while 1.0 + epsilon > 1.0:
    epsilon = epsilon / 2.0

# It's one step too small now so double
# it to move back one step.
epsilon = epsilon * 2.0

# And output the result.
print epsilon
Output:
2.22044604925e-16

Start with two non-negative numbers which are definitely larger and smaller than the machine epsilon. These define an interval which contains the machine epsilon. We repeatedly calculate the mid-point between them and determine if it is larger or smaller than the epsilon and change the bounds of the interval accordingly. We keep going until the interval is short enough.
epsilon2.py
too_large = 1.0
too_small = 0.0
tolerance = 1.0e-27

while too_large - too_small > tolerance:

    estimate = (too_large + too_small) / 2.0

    if 1.0 + estimate > 1.0:
        too_large = estimate
    else:
        too_small = estimate

print too_small, '< epsilon <', too_large
Output:
1.11022302463e-16 < epsilon < 1.11022302463e-16

3149

主题

8386

回帖

6万

积分

$\style{scale:11;fill:#eff}꩜$

积分
65391
QQ

显示全部楼层

 楼主| hbghlyj 发表于 2022-8-3 07:39
《你不懂JS:类型与文法 – 小数值

使用二进制浮点数的最出名(臭名昭著)的副作用是(记住,这是对 所有 使用 IEEE 754 的语言都成立的 —— 不是许多人认为/假装 在 JavaScript 中存在的问题):

0.1 + 0.2 === 0.3; // false

从数学的意义上,我们知道这个语句应当为 true。为什么它是 false

简单地说,0.10.2 的二进制表示形式是不精确的,所以它们相加时,结果不是精确地 0.3。而是 非常 接近的值:0.30000000000000004,但是如果你的比较失败了,“接近”是无关紧要的。

手机版|悠闲数学娱乐论坛(第3版)

GMT+8, 2025-3-4 15:55

Powered by Discuz!

× 快速回复 返回顶部 返回列表