Forgot password?
 Create new account
View 80|Reply 1

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

[Copy link]

3147

Threads

8493

Posts

610K

Credits

Credits
66163
QQ

Show all posts

hbghlyj Posted at 2022-8-3 07:24:21 |Read mode
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

3147

Threads

8493

Posts

610K

Credits

Credits
66163
QQ

Show all posts

 Author| hbghlyj Posted at 2022-8-3 07:39:17
《你不懂JS:类型与文法 – 小数值

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

0.1 + 0.2 === 0.3; // false

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

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

手机版Mobile version|Leisure Math Forum

2025-4-20 22:23 GMT+8

Powered by Discuz!

× Quick Reply To Top Return to the list