Trying to make loop for a function that stops after the result is lower than a certain value

2024/10/5 17:28:13

I'm taking a beginner python class and part of an exercise we were given was this:

The point x with the property x= sin(x)−ax+ 30 is called a fixed point of the function f(x) = sin(x)−ax+ 30. It can be computed with the so-called fixed point iteration: x(i+1)= sin(x(i))−ax(i)+ 30, where the superscript (i) denotes an iteration counter. Here you find a piece of Python code which performs the first 200 steps of this

x=0.5
a=0.5
for i in range(200):x = sin(x) - a*x + 30
print('The result after {num} iterations is {res}.'.format(num=i, res=x))

Modify the code in such a way that it stops iterating as soon as |x(i+1)−x(i)| < 10−8. Furthermore it should print a little message if this condition was not met within 200 iteration steps. Test your code with a= 0.5 and a= 8

I've tried to do this but am not getting anywhere with it. This is what I have so far, any help would be much appreciated.

x = 0.5
a = 8
iterations = 0for i in range(y):x = sin(x) - a*x + 30if abs(x**(i+1) - x**i) < 1.e-8:breakelif i > 200:iterations += 1print('The result after {num} iterations is {res}.'.format(num=i, res=x))if iterations > 0:print('The condition was not met within 200 iteration steps.')
Answer

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 sinx = 0.5
a = 0.5
for i in range(200):x1 = sin(x) - a*x + 30print(i, x)  # remove before submittingif abs(x1 - x) < 1.e-8:breakx = 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 is 20.649274368307022.The condition was not met within 200 iteration steps.
The result after 199 iterations is -1.1949487767945635e+181.
https://en.xdnf.cn/q/119901.html

Related Q&A

python url extract from html

I need python regex to extract urls from html, example html code :<a href=""http://a0c5e.site.it/r"" target=_blank><font color=#808080>MailUp</font></a> <…

Regex match each character at least once [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

How to cluster with K-means, when number of clusters and their sizes are known [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 1…

Converting German characters (like , etc) from Mac Roman to UTF (or similar)?

I have a CSV file which I can read in and at all works fine except for the specific German (and possibly other) characters. Ive used chardet to determine that the encoding is Mac Roman import chardetde…

Caesar cipher without knowing the Key

Hey guys if you look at my code below you will be able to see that i was able to create a program that can open a file decode the content of the file and save it into another file but i need to input t…

how to convert u\uf04a to unicode in python [duplicate]

This question already has answers here:Python unicode codepoint to unicode character(4 answers)Closed 2 years ago.I am trying to decode u\uf04a in python thus I can print it without error warnings. In …

How can I display a nxn matrix depending on users input?

For a school task I need to display a nxn matrix depending on users input: heres an example: 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0(users input: 5) And here is my code until now:n = int(inpu…

How to launch 100 workers in multiprocessing?

I am trying to use python to call my function, my_function() 100 times. Since my_function takes a while to run, I want to parallelize this process. I tried reading the docs for https://docs.python.org/…

Indexes of a list Python

I am trying to find how to print the indexes of words in a list in Python. If the sentence is "Hello world world hello name") I want it to print the list "1, 2, 2, 1, 3")I removed a…

str object is not callable - CAUTION: DO NO USE SPECIAL FUNCTIONS AS VARIABLES

EDIT: If you define a predefined type such as: str = 5 then theoriginal functionality of that predefined will change to a new one. Lesson Learnt: Do not give variables names that are predefined or bel…