I was writing a method that would calculate the value of e^x. The way I implemented this in python was as follows.
import math
def exp(x):
return sum([
x**n/math.factorial(n)
for n in range(0, 100)
])
This would return the value of e^x very well. But when I tried to implement the same method in c#, it didn't output the same value as it did in python. The following was the implementation in c#.
static double exp(int x)
{
double FinalAnswer = 0;
for (int j = 0; j <= 100; j++)
{
FinalAnswer += (Math.Pow(x, j))/Factorial(j);
}
return FinalAnswer;
}
The output for this code was an infinity symbol at first. To resolve this I just reduced the number of times the loop ran. The output of the code in c# where the loop only ran 10 times was pretty close to the output in python where the loop ran 100 times. My question is that what is going on between the two loops in different programming languages. At first I thought that the expression that I was using in my method to calculate e^x was converging quickly. But how does a loop that runs 10 times produce an output that matches the output of a loop that runs 100 times.
Also, When I increased the for loop in c# to 20 and 30, the values of e^x for x > 3 were way off. Could someone explain what is going on here?
j < 100
, your python range stops at 99...92, 93, 94, 95, 96, 97, 98, 99]
– Lynndouble
is a hardware native type with precision limits (you can see this with3**50
yielding the int717897987691852588770249
in python and in c#(long)Math.Pow(3,50)
yields-9223372036854775808
). – Fawkes