将数字保存为变量 [英] Saving number to variable

查看:123
本文介绍了将数字保存为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to find smallest positive number (which doesn't equal to 0) and save it to variable "small" and largest positive number which is less than infinity (math.inf) and save it to variable "great". My code looks so far like this:

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".如何保存所需的数字而不必从我从代码中获得的列表中手动输入它们?

It prints list of numbers but the problem is that Python saves "small= 0" and "great= inf". How can I save required numbers without having to manually input them from the list which I get from my code?

推荐答案

x = float(1)    
small = x

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

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

This will get you smallest possible(almost) float. Hope you can now figure out largest too similarly.

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

The best and easiest solution for finding smallest and largest possible float is:

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:

Another solution is using 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提供的值与其他方法不同,我不确定为什么,也许其他人可以对此有所启发.

All methods provides same max value, but for min value sys.float_info provides different value than others, I am not sure why, maybe someone else can enlighten me regarding this.

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

nextafter(x, y) source
The nextafter(), nextafterf(), and nextafterl() functions return the next representable floating-point value following x in the direction of y.

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

If y is less than x, these functions will return the largest representable number less than x.

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

If x equals y, the functions return y.

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

numpy.nextafter(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = < ufunc 'nextafter'> source
Return the next floating-point value after x1 towards x2, element-wise.

这篇关于将数字保存为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆