计算最接近的数字numpy

ric*_*ter 3 python numpy epsilon

我正在尝试将最接近的数字计算为0,但到目前为止无法得到我想要的数字.

我有一个非常简单的代码;

y = 0.0
x = 0.1
while (y + x > y):
    x = x/2.0
x*2
Run Code Online (Sandbox Code Playgroud)

但我一直得到0.0作为输出.我怎样才能解决这个问题

小智 5

我想你想继续分割,直到x变得如此之小,它变为零(浮点格式).在循环的最后一次迭代中,x最终变为零,循环条件变为假: 0.0(y) + 0.0(x) > 0.0(y).在最后一行,您尝试通过乘以2来检索x值.但是x已经为零,因此结果也为零.数学上是完全有意义的,但浮点值在那时已经为零.

为了保持最新的非零值,请使用第二个变量:

y = 0.0
x = 0.1
smallest_x = x

while (y + x > y):
    smallest_x = x
    x = x/2.0
x*2
Run Code Online (Sandbox Code Playgroud)

或者,您可以事先检查x再次分割后是否为零:

y = 0.0
x = 0.1
while (y + x/2.0 > y):   //checking if the next division makes x to zero
    x = x/2.0
x*2
Run Code Online (Sandbox Code Playgroud)

或采取不同的方法来获得最小的x:

x = 1.0
while (x/2.0 != 0):
    x = x/2.0
Run Code Online (Sandbox Code Playgroud)