Difference makes the DIFFERENCE
Exercise 2
def factorial(n):
product = 1
for i in range(n):
# print(i, product)
product *= (i + 1)
return product
print(factorial(3))
def factorial_recursive(n):
if n > 1:
return n * factorial_recursive(n - 1)
else:
return 1
print(factorial_recursive(3))
def compute_ratio(x, n):
ratio = x**n / factorial(n)
return ratio
compute_ratio(2, 3)
def compute_sum(x, N):
sum = 1
for i in range(N):
sum += compute_ratio(x, i + 1)
return sum
print(compute_sum(2, 3))
def compute_sum_epsilon(x, epsilon):
sum = 1
var = epsilon
i = 1
while var >= epsilon:
var = compute_ratio(x, i)
sum += var
i += 1
return sum
print(compute_sum_epsilon(2, 0.01))
print(compute_sum(2, 100))
def compute_sum_epsilon(x, epsilon):
sum = 1
i = 1
while True:
var = compute_ratio(x, i)
sum += var
i += 1
if var < epsilon:
break
return sum
print(compute_sum_epsilon(2, 0.01))
p = -1.5
q = 7.1
v1 = compute_sum(p, 100) * compute_sum(q, 100)
v2 = compute_sum(p + q, 100)
print(v1, v2, v2 - v1)
for i in range(10):
print(i, compute_sum(i, 100))