将数字保存到变量

时间:2018-10-11 06:47:19

标签: python python-3.x list variables

我必须找到最小的正数(不等于0)并将其保存到变量“ small”中,将最大的正数小于无穷大(math.inf)并将其保存到变量“ great”中。到目前为止,我的代码如下:

x = float(1)
import math 

small = x/2
while small > 0:
    small = small/2
    print(small)

y = float(1)    
great = y*2
while great < math.inf:
    great = great*2
    print(great)

它打印数字列表,但问题是Python保存了“ small = 0”和“ great = inf”。如何保存所需的数字而不必从我从代码中获得的列表中手动输入?

2 个答案:

答案 0 :(得分:0)

x = float(1)    
small = x

while small > 0:
    real_small = small
    small = small/2
print(small) # 0.0
print(real_small) # 5e-324

这将使您的浮标最小(几乎)。希望您现在也能找出最大的相似值。

找到最小和最大可能浮动的最佳和最简单的解决方案是:

import numpy as np
import math

>>> # Smallest
>>> np.nextafter(0, 1)
5e-324


>>> # Largest
>>> np.nextafter(math.inf, 0)
1.7976931348623157e+308
>>> np.nextafter(np.float64(math.inf), 0)
1.7976931348623157e+308

另一个解决方案是使用sys.float_info:

>>> import sys
>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)

所有方法都提供相同的最大值,但是对于最小值sys.float_info提供的值却与其他方法不同,我不确定为什么,也许其他人可以对此有所启发。

下一个(x,y) source
nextafter(),nextafterf()和nextafterl()函数返回 在x方向上跟随x的下一个可表示浮点值 的y。

如果y小于x,则这些函数将返回最大的 小于x的可表示数字。

如果x等于y,则函数返回y。

numpy.nextafter(x1,x2,/,out = None,*,其中= True,铸造='same_kind',order ='K',dtype = None,subok = True [,签名,extobj ])= source
将x1之后的下一个浮点值向x2逐元素返回。

答案 1 :(得分:0)

您应该在small变为0之前中断第一个循环,而great之前的第二个循环等于无穷大:

import math

small = 1
while True:
    if small / 2 == 0:
        print(small)
        break
    small /= 2

great = float(1)
while True:
    if great * 2 == math.inf:
        print(great)
        break
    great *= 2

这将输出:

5e-324
8.98846567431158e+307