Reputation: 1
This is the task: Write a function that has a limit(lim) and Returns prod
and Count
, where prod is defined as (1+1/1**2)(1+1/2**2)(1+1/3**2)
...
Count is amount of times it has ran. It supposed to end when prod is less than the limit. this is what I got so far: (I fixed the code With the help I got from the responses)
def variabel(n):
return 1+1/n**2
def tol():
tol1 = float(input("Hva er grensen?"))
prod = 1
prod2 =2
prod3 = 2
n = 1
count = 0
while tol1 < prod2:
prod3 = variabel(n)*prod
prod2 = prod3-prod
prod = prod3
n += 1
count += 1
if tol1 >= prod2:
print("Produktet ble", prod, "etter", count, "itterasjoner")
tol()
Upvotes: 0
Views: 454
Reputation: 113978
first a hint that will help you solve this type of problem and help keep your code nice and neat.
break your code into smaller sub problems, and create a helper method for each subproblem
problem 1: solve 1/n**2 in generic way
def default_function(x):
return 1/x**2
problem 2: create a series from this
def my_series(start=1,func=default_function):
#return 1/n**2 for ever
for i in itertools.count(start):
yield func(i)
this lets you try various things for example if i wanted to print the values forever
for value in my_series(): # will print forever...
print(value)
time.sleep(1)
if you just wanted the first 10 values
for i, value in zip(range(1,11),my_series()):
print("{0}. {1}".format(i,value))
if you wanted to plot the first 100 values
from matplotlib import pyplot as plt
xs_and_ys = zip(range(1,101),my_series()) #[(1,series[0]),(2,series[1]),...]
xs,ys=zip(*xs_and_ys) # transpose into separate xs and ys
plt.plot(xs,ys)
plt.show()
now you will notice i didnt quite finish your homework for you, instead i hope that ive given you the tools that you can use to solve your 3rd subproblem
problem 3: return series until the product of them is greater than or less than some threshold
Upvotes: 2