执行算术代码时会产生不寻常的结果

时间:2016-03-17 15:32:44

标签: python math

Python脚本似乎做错误的算术。

import _thread
import time

def mult(pixel : int, multiplier : tuple) -> float:
    "multiplies either r,g,b pixel by row vector (0.257, 0.504, 0.098),(-0.148,-0.291,0.439),(0.439,-0.368,-0.071))"

    sum=0
    for mul in multiplier:
        sum += (pixel * mul)
        print(sum)
    return sum

redMul = [0.257, 0.504,0.098]
greenMul = [-0.148, -0.291, 0.439]
blueMul = [0.439, -0.368,-0.071]

redAdd = 16
greenAdd = 128
blueAdd = 128

try:
   _thread.start_new_thread(mult,(1,blueMul))
except:
    print("Error: unable to start thread")

代码输出:

0.439
0.07100000000000001
1.3877787807814457e-17

期待:

0.439 
0.071
0

此错误的原因是什么?如何解决?

2 个答案:

答案 0 :(得分:1)

sum = round(sum, 3))

将float限制为3个小数点,然后执行算术

def mult(pixel : int, multiplier : tuple) -> float:
    "multiplies either r,g,b pixel by row vector (0.257, 0.504, 0.098),(-0.148,-0.291,0.439),(0.439,-0.368,-0.071))"

    sum=0
    for mul in multiplier:
        sum += (pixel * mul)
        sum = round(sum, 3)
        print(sum)
    return sum

答案 1 :(得分:1)

Python脚本不会执行不正确的算术,它只是浮​​点运算的方式。

使用float(Python中的双浮点精度)时需要注意的主要原则是它是实际值的近似。除非该值具有幂2的分母 - 如1,2,4,0.5,0.25等,否则该值不能由float精确表示。它总是近似,最高可达15/16位。

因此你所有的结果:

0.439
0.07100000000000001
1.3877787807814457e-17

是正确的......直到15/16的有效数字,即:

0.439
0.0710000000000000
0.000000000000000 #(thus you have 1 e-17 as your 17-th digit)

float不保证超出第15/16位的精度

如果您确实需要高于15-16位数的精度,请考虑使用decimal