Longdouble(1e3000) becomes inf: What can I do?

断了今生、忘了曾经 提交于 2019-12-11 02:29:14

问题


(Most other related questions in the web concern conversion between C's longdouble and python's. This question is different.)

I do not see why I cannot correctly get a longdouble in python like this:

In [72]: import numpy as np

In [73]: np.longdouble(1e3000)
Out[73]: inf

It seems that I need to let my python console know 1e3000 is a longdouble instead of double. How can I do that


回答1:


The problem is that by using an expression like ...(1e3000), the Python parser has to calculate what is inside the parentheses first, and pass the result to the function call. Long double is not a native type, therefore, the value inside the parentheses is inf - which is passed to the longdouble constructor. The fact the string version fails could maybe be considered a bug in NumPy - it indicates the string is converted to a Python float (which is a "float64" or "double" in C) internally, possibly using the normal Python float constructor.

The workaround is to build the long double object first, with a value that is compatble with a Python float, and them multiply it to get to the desired value. If you need to do that with several values, use a NumPy array instead of a single value:

>>> x = np.longdouble(10)
>>> x
10.0
>>> x **= 3000
>>> x
9.9999999999999999999e+2999



回答2:


Python doesn't have "long doubles". By using scientific notation, you are making a float literal. Those cannot represent 1e3000, so you get inf. If you use integers, you might be able to do what you need: 10**3000.



来源:https://stackoverflow.com/questions/30419534/longdouble1e3000-becomes-inf-what-can-i-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!