Euler's Number Algorithm

Euler’s Number Algorithm

What we are asked to do is to find the form of any number to the power of e limited to m.

a = int(input("please give the number which refer to x0: "))
b = int(input("please give the number which refer to m: "))
pw = 1
c = a
fc = a
temp = a
res = 0
for i in range(2, b + 1, 1):
  while i > 0:
    pw = pw * a
    if c > 1:
      fc = fc * (c - 1)
    c = c - 1
    i = i - 1
  temp = temp + 1
  c = temp
  res = pw / fc + res
  fc = temp
  pw = 1
print(res + a + 1)
2 Likes

So, you’re attempting to compute x raised to the power of Euler’s number e, limited to the precision of m?

2 Likes

Exactly. Actually, this is called Taylor sequence and the desired digits of the Euler number are calculated with this method.

2 Likes

I’m pretty sure this would work fine, I haven’t tested it but:

import math

def _compute(x, m):
    result = 0
    for i in range(m):
        result += (x ** i) / math.factorial(i)
    return result
2 Likes

I think your solution looks pretty good and so easy to understand. This is my computer lab exam question and we mustn’t use any library and also power operator(**) in this exam. I wan’t to share my solution. Thanks for your reply :slightly_smiling_face:

2 Likes

You can’t use built-in libraries?

1 Like

I’m guessing you could use built-in libraries, but if you can’t use this:

def _compute(x, m):
  _x = sum(
      (x if i == 0 else x * term[-1]) / (factorial := 1 if j == 0 else factorial * j)
      for i, term in enumerate([[1] for _ in range(m)])
      for j in range(i + 1)
  )
  return _x
2 Likes

@Berkayasd If this solved your problem, please mark it as a solution.

1 Like

Well if no imports can be used, we can improve some part of @Sky ’s program

To


def _compute(x, m):
    result = 1
    last_factorial = 1
    last_exponent = 1
    for i in range(m):
        result += (last_exponent / last_factorial)
        last_factorial *= i
        last_exponent *= x
    return result

I also improved the performance by a bit by saving the last factorial&exponent and multiply them with a new one instead of re-calculating factorials&exponents
And it kept it’s simplicity compared to the later solution given by @Sky

However, if m is the precision of the calculation. From what I remembered, m greater than a number below 30 (I forgot the exact number) will not be more accurate. This is because there is a limit for how many digits after decimal point is allowed in float variables. If m need to be large, the package Decimal have to be used for better precision, without import I don’t think it could work.

4 Likes

My code is more optimized since it uses a single loop structure and avoids repetitive calculations by using a single expression to compute the sum. So, I am willing to sacrifice a bit of readability just to get that extra optimization.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.