python 中的精确除法
Exact division in python
我是 python 的新手,我编写了一个程序,将值从区间 [-7000,18000] 缩放到区间 [-1,1]。
desired_upper_bound = 1.0
desired_lower_bound = -1.0
max_value = 18000.0
min_value = -7000.0
value = -7000.0
slope = (desired_upper_bound - desired_lower_bound) / (max_value - min_value)
print(slope)
intercept = desired_upper_bound - (slope * max_value)
print(intercept)
transformed_value = slope * value + intercept
print(transformed_value)
'transformed_value' 的确切结果应该是 -1,尽管控制台提供:-1.0000000000000002。对于我的其余工作,当值不在区间内时可能会导致很多问题,所以我想知道如何解决这个问题。
我想计算“1”的数学正确结果并显示在控制台中。我做错了什么?
发生这种情况是因为浮点运算不精确。引用维基百科上的 floating-point arithmetic article:
floating-point arithmetic (FP) is arithmetic using formulaic
representation of real numbers as an approximation so as to support a
trade-off between range and precision.
由于这只是一个近似值,您会遇到类似的情况。如果你想强制一些数字进入一个特定的时间间隔,你可以检查它们是否没有超过它,如果超过了,你可以像这样四舍五入:
if transformed_value <= -1:
transformed_value = round(transformed_value)
我是 python 的新手,我编写了一个程序,将值从区间 [-7000,18000] 缩放到区间 [-1,1]。
desired_upper_bound = 1.0
desired_lower_bound = -1.0
max_value = 18000.0
min_value = -7000.0
value = -7000.0
slope = (desired_upper_bound - desired_lower_bound) / (max_value - min_value)
print(slope)
intercept = desired_upper_bound - (slope * max_value)
print(intercept)
transformed_value = slope * value + intercept
print(transformed_value)
'transformed_value' 的确切结果应该是 -1,尽管控制台提供:-1.0000000000000002。对于我的其余工作,当值不在区间内时可能会导致很多问题,所以我想知道如何解决这个问题。
我想计算“1”的数学正确结果并显示在控制台中。我做错了什么?
发生这种情况是因为浮点运算不精确。引用维基百科上的 floating-point arithmetic article:
floating-point arithmetic (FP) is arithmetic using formulaic representation of real numbers as an approximation so as to support a trade-off between range and precision.
由于这只是一个近似值,您会遇到类似的情况。如果你想强制一些数字进入一个特定的时间间隔,你可以检查它们是否没有超过它,如果超过了,你可以像这样四舍五入:
if transformed_value <= -1:
transformed_value = round(transformed_value)