1
>>> import math

#defining first function
>>> def f(a):
        return a-math.sin(a)-math.pi/2

#defining second fuction
>>> def df(a):
        return 1-math.cos(a)

#defining third function which uses above functions
>>> def alpha(a):
        return a-f(a)/df(a)

How to write a code in which alpha(a) takes a starting value of a=2, and the solution of alpha(2) will become the input the next time. For eg: let's suppose alpha(2) comes to 2.39 , hence the next value would be alpha(2.39) and go on {upto 50 iterations}. Can somebody please help me a bit. thanks in advance.

4
  • Are you looking to do this while the program is running, or are you looking to be able to quit the application and continue with the last used number? Commented Jul 24, 2017 at 23:41
  • Use a for-loop? Commented Jul 24, 2017 at 23:41
  • @idjaw while the program is running.Thanks Commented Jul 24, 2017 at 23:49
  • yes, thanks i will try using for-loop Commented Jul 24, 2017 at 23:50

2 Answers 2

2

You can let the program iterate with a for loop, and use a variable to store the intermediate results:

temp = 2                # set temp to the initial value
for _ in range(50):     # a for loop that will iterate 50 times
    temp = alpha(temp)  # call alpha with the result in temp
                        # and store the result back in temp
    print(temp)         # print the result (optional)

print(temp) will print the intermediate results. It is not required. It only demonstrates how the temp variable is updated throughout the process.

Sign up to request clarification or add additional context in comments.

2 Comments

So, at some point the values keep repeating .Is there any program to choose the repeating value out of the 50 iteration??
@GarrySaini: usually if they start repeating, you can pick the last value. That means that you have found a fixed point of the program.
0

You can objectify it.

import math

class inout:
    def __init__(self, start):
        self.value = start
    def f(self, a):
        return a-math.sin(a)-math.pi/2
    def df(self, a):
        return 1-math.cos(a)
    def alpha(self):
        self.value = self.value-self.f(self.value)/self.df(self.value)
        return self.value

Then create an inout object and each time you call its alpha method it will give the next value in the series.

demo = inout(2)
print(demo.alpha())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.