1

I am trying to write a program that iterates for me in the form of xn+1 = xn2 + c. How do I do this?

For example, for c = 1 and x0 = 1/2

(1/2)2 + 1 = 5/4,
(5/4)2 + 1 = 25/16 + 1 = 41/16
... etc

My code doesn't work here:

def main():
   import math
   print("This program iterates a function of the form x^2 + c:")
   x=complex(input("Enter a seed value:"))
   c=complex(input("Enter a value for c"))

for i in range(50):
   f(0) = x*x + c
   f(i) = f(i-1)*f(i-1) + c
   print(f(i))
main()

Python doesn't allow me to use f(0) or f(i) like matlab, what's the alternative to this?

4
  • I get "can't assign function call". This is my first few times using Python so I don't know what to use here. I need to know what tools I can use. Commented May 5, 2012 at 6:25
  • 1
    I think you need to look into python basics some more. There's a lot of errors here. Have you worked your way through any python tutorials? Commented May 5, 2012 at 6:26
  • I've written a code for a function before yes. The tutorials that I've studied were spread out in 2 weeks, so this is still a new language. Commented May 5, 2012 at 6:32
  • 1
    f(n) in python is a function call instead of an array operation Commented May 5, 2012 at 6:36

5 Answers 5

2

Tabbing is critical in python, please try the code below. This is a long shot to guess what your intentions are, but it brings you much closer to a final result

def main(x):
    import math
    print("This program iterates a function of the form x^2 + c:")
    c = complex(input("Enter a value for c"))

    print "C : %s" % c

    f = [x * x + c]

    for i in range(1, 50):
        f.append(f[i - 1] * f[i - 1] + c)

    print f

main(2)
Sign up to request clarification or add additional context in comments.

10 Comments

Except f(i) = f(i-1) + c Makes no sense.
After reading through the code, I was actually just about to say that... What in the world are you trying to do lol
I am so sorry Bryan that is my fault. I've revised my code according to what is supposed to happen.
My main issue here is, what can I use instead of f() since Python doesn't seem to accept it?
I've provided that in the code, you'll want to use .append, and f[i] to obtain a value previously stored. Btw, I've extended the example to actually base the multiplication off of the previous value
|
2

If you're not intereseted in keeping all the partial results, you could iterate like this:

import math
print("This program iterates a function of the form x^2 + c:")
x = complex(input("Enter a seed value:"))
c = complex(input("Enter a value for c"))

f = x * x + c
for _ in range(50):
   f = f * f + c
   print(f)

7 Comments

@RikPoggi: Nope. Mine's iterative, just like yours :) The only difference is that I've extracted the mathematical function from main() into f() making it easier to read, test and maintain.
@Johnsyweb: Oh, that's right. I gave it a too quick look. I like it anyway because it's DRY :)
@RikPoggi: The resursive solutions should never be recommended for such iterative functions (and Johnysweb did not) as they are extremely inefficient. For example, it is almost a joke to solve Fibonacci recursively -- some students will remember it as the recommened way :)
@pepr a calculation being recursive does not necessarily imply it's less efficient than an iterative one. In fact, they're provably equivalent in expressive power, and only differ depending on how your architecture or VM deals with tail call recursion.
@pepr I don't mean to be contradictory, but that is provably false. With tail calls, recursion is precisely equivalent to iteration not only in expressive power but in achievable efficiency. If you're not familiar with the concept, this may help: wiki.umn.edu/CSCI1901/IterationVsRecursion
|
1

Let's call your function f:

def f(x, c):
    return x * x + c

Then in main() you can call it like this:

def main():
    n = complex(input("Enter a seed value: "))
    c = complex(input("Enter a value for c: "))

    print n
    for term in range(50):
        n = f(n, c)
        print n

With each iteration, n is reassigned to the return value of the f with the previous value of n.

1 Comment

Creative, wow. I can definitely respect computer science majors now.
1

There is a special mechanism in Python that is called a generator function. It returns an object that remembers the last state and executes the body of a function with the values from the previous call (an iterator).

It differs syntactically from normal functions only by using the yield command instead of return. You can typically use such a generator function on places where iterators are expected, i.e. for-loop, container constructors, etc. See the code:

def f(x, c, n=5):
    while n > 0:
        yield x        # returns x0 as first value
        x = x * x + c  # this value is to be returned next time
        n -= 1         # decrement the sequence counter


# Using the generator function in a for loop.
for value in f(1/2, 1, 14):  # I want 14 members of the sequence
    print(value)

# Using the generator function to build a list of the values.
print('----------------------------------')
lst = list(f(1/2, 1, 10))    # 10 members wanted here
print(lst)


# Using the standard module called fractions for the same function.
print('==================================')
from fractions import Fraction as frac

# Using the generator function in a for loop.
for value in f(frac(1, 2), 1):  # default number of loop used here
    print(value)

# Using the generator function to build a list of the values.
print('----------------------------------')
lst = list(f(frac(1, 2), 1, 10))  # 10 members wanted here
print(lst)

# Generating Mandelbrot set values.
print('==================================')
# Using the generator function in a for loop.
for value in f(complex(0), complex(0, 1)):  # default number of loop used here
    print(value)

Python does not compute the expression symbolically, as the matlab does. However, it has the standard module fractions that has the Fraction class to represent the fractions. You can use the same generator function also for that type as it defines its own multiplication and addition. As Python integer is less limited than the float, you may get bigger results with the Fractions (if it makes sense at all). But you probably want to generate a Mandelbrot set, right?

It shows on my console (wrapped lines):

0.5
1.25
2.5625
7.56640625
58.25050354003906
3394.1211626681034
11520059.466871478
132711770120256.16
1.7612413928451715e+28
3.1019712438712e+56
9.62222559780384e+112
9.258722545503146e+225
inf
inf
----------------------------------
[0.5, 1.25, 2.5625, 7.56640625, 58.25050354003906, 3394.1211626681034, 11520059.
466871478, 132711770120256.16, 1.7612413928451715e+28, 3.1019712438712e+56]
==================================
1/2
5/4
41/16
1937/256
3817505/65536
----------------------------------
[Fraction(1, 2), Fraction(5, 4), Fraction(41, 16), Fraction(1937, 256), Fraction
(3817505, 65536), Fraction(14577639392321, 4294967296), Fraction(212507588699293
047863318657, 18446744073709551616), Fraction(4515947525478824258458249067737177
3490882293292495105, 340282366920938463463374607431768211456), Fraction(20393782
05287831607501825305820853979646214602081433287459323242821411496740800167480972
336912829578600961, 115792089237316195423570985008687907853269984665640564039457
584007913129639936), Fraction(41590634642030170391815210870941032988232016881852
69467060076200306147021769623813726880369383179868466442311933392597163786089664
61843166606956164602440721448188927878363156181727061624343416854647005907620761
7, 13407807929942597099574024998205846127479365820592393377723561443721764030073
546976801874298166903427690031858186486050853753882811946569946433649006084096)]

==================================
0j
1j
(-1+1j)
-1j
(-1+1j)

Comments

0

good day.

# x_(n+1) = x_(n)^2 + c

def f(n,c):
    a=0
    while a < n:
        a +=1
        yield a * a + c

now you can use f as generator

if __name__ == '__main__':
    for element in f(100, 0):
        print element

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.