Search code examples
python-2.7numpyfloating-pointprecisionexp

Why is that I'm able to successfully return a large np.float128 but when I try to create the same np.float128 in numpy I just get inf?


I'm writing a function to take the exponent of a large number:

def exp_large_float(x):
    return np.exp(np.float128(np.array([x])))

result = exp_large_float(800.)
print(result)
>>> [2.72637457e+347]

print(result.dtype)
>>> float128

I'm testing that result is what I intend so I want to create a "ground truth" array and compare it to the output of exp_large_float:

ground_truth = np.float128(2.72637457e+347)
print(ground_truth)
>>> inf

Why is that I'm able to successfully return a np.float128 of 2.72637457e+347 but when I try to create this same thing in numpy I just get inf?

I'm using python version 2.7.15.


Solution

  • As pointed out by @Warren Weckesser your code doesn't work because

    2.72637457e+347
    

    is a float literal in Python so it is interpreted as standard (presumably 64bit) float and becomes inf before it is passed on to the float128 factory.

    You can avoid this by passing your argument as a string.

    ground_truth = np.float128("2.72637457e+347")