1

I created this function using python

import numpy as np
p1=1/2


def qud(x,p):
    x_sqr = x**2
    x_qud = x**3
    pn=x_sqr*p
    return x_sqr ,x_qud,pn

I need to iterate this function multiple times , by giving the value of pn in the previous iteration.

I tried this without a for loop like this,

First iteration : sqr1, qud1 ,pnew = qud(2,p1)

Second iteration : sqr2, qud2 ,pnew1 = qud(2,pnew)

where i have used the value pnew which obtained from the first iteration.

Third iteration : sqr3, qud3 ,pnew2 = qud(2,pnew1) so on.

Now i wanted to modify my code so that values are going to stored using a for loop , when the number of iterations are given .But my code didnt work.

My code as follows,

i=4
sqr = np.zeros(i)
qud = np.zeros(i)
p1 = np.zeros(i)
sqr[0],qud[0],p1[0] = qud(2,p1)

for j in range (1,3) :
    sqr[j],qud[j],p1[j] = qud(2,p1[j-1])

can any one suggest anything so that this works ?

Thank you

2
  • In what way did it not work? Did it throw an exception? Please include the exception here if so. Was it just incorrect? Commented Jul 18, 2019 at 1:08
  • @Craig That was a typo. When i did using index j too , it didnt work Commented Jul 18, 2019 at 1:14

1 Answer 1

3

A pythonic way to do this is to create a generator. The generator will maintain state and you can call next() or use any of the many python itertools, maps, filters, etc. Here's one way to get the first four values:

from itertools import islice

def qud(x,p):
    x_sqr = x**2
    x_qud = x**3
    while True:
        p = x_sqr*p                        # update p
        yield x_sqr ,x_qud,p               # yield instead of return

my_iterator = qud(2,1/2)                   # create an iterator based on itial values

for values in islice(my_iterator, 0, 4):   # loop over an islice 
    print(values)

This will keep making values as long as you keep iterating over it.

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

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.