0

I have written a simple code to approximate exponential integral function (Ei function). This function has already been implemented in other libraries (like mpmath) but for some reasons, I do not want to use them. In this approximation there are some mathematical implementation (like factorial). My code works fine for relatively small values when the number of required terms for function approximation is less than 100 but for approximation of large numbers (For example 200) I need to increase the number of terms to above 200-300 terms. In these cases I get this error:

OverflowError: int too large to convert to float

I also searched about this error. People have suggested to use Decimal to resolve this issue but I could not get it to work. I appreciate any help to fix this issue. Here is my code:

#This code has been  written for approximation of Ei(200) with 150 terms that gives the error

import numpy as np

gamma = 0.5772156649  # gamma is a constant

def Ei(X, k, b):  # Ei (X: number , k : number of terms in approximation, b: Approximation of entire function which is part of approximation)

    for s in range(1, k + 1):  # Factorial
        fact = 1
        for i in range(1, s + 1):
            fact = fact * i

        b += (pow(-1., s + 1) * pow(-X, s) / (s * fact))

    return gamma + np.log(X) - b

# Compare with Ei function in mpmath
from mpmath import ei

print (ei(200))

B = Ei(200, 150, 0)  # Gives OverflowError Error
print (B)
Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51
Leo
  • 479
  • 2
  • 6
  • 16
  • 1
    Well, one standard approach is to restate the terms so that you don't need to explicitly calculate factorials. How about rewriting `(- X)^s / (s * s!)` as (1/s) times the product of `(- X)/n` for n from 1 to s? – Robert Dodier Mar 31 '20 at 04:45
  • I tried what you suggested but it returns "nan". Are you getting the same thing? If it works, could you please your implementation? – Leo Mar 31 '20 at 19:42
  • Leo, my advice is that you edit your problem description to show the modified code which you have tried and exactly what output you are getting. My advice is to leave the original problem statement as it is, and just put a section with "EDIT:" below it, so people can see the original code and the modified code. – Robert Dodier Mar 31 '20 at 22:49
  • OK, some more advice. Try it with a smaller value of X. How about 2 instead of 200? If that seems to work, how about 20? Try larger values after you get it working for smaller values. – Robert Dodier Mar 31 '20 at 23:01
  • Thanks Robert. I had a mistake in the code. I modified it and now it is working good. I appreciate your help. – Leo Apr 01 '20 at 17:08

0 Answers0