Trying To Make Loop For A Function That Stops After The Result Is Lower Than A Certain Value
Solution 1:
To see what happens during the iteration, I advise adding print(i, x)
to the loop in either the original code (after being corrected with the needed indent) or your code. You can remove it before submitting.
The original and your code lack from math import sin
. Code posted should be ready to run, including needed imports.
Your posted code neglects to define y=200
, but there is no need to add that for the problem as specified. In any case, for i in range(y)
will give i the values 0, 1, ..., 199. Your condition i > 200
will never be true. The easiest way to do something if the loop does not break is to use an else:
clause. Or you can replace iterations
with the more descripting failure
and correct your condition.
Combined with Tom K's comment, possible code that works is
from math import sin
x = 0.5
a = 0.5for i in range(200):
x1 = sin(x) - a*x + 30print(i, x) # remove before submitting
ifabs(x1 - x) < 1.e-8:
break
x = x1
else:
print('The condition was not met within 200 iteration steps.')
print('The result after {num} iterations is {res}.'.format(num=i, res=x))
This prints for a = .5 and 8:
The result after 59 iterations is20.649274368307022.
The condition was not met within200 iteration steps.
The result after 199 iterations is-1.1949487767945635e+181.
Post a Comment for "Trying To Make Loop For A Function That Stops After The Result Is Lower Than A Certain Value"