9

How can I solve this equation

x3 + x - 1 = 0

using fixed point iteration?

Is there any fixed-point iteration code (especially in Python) I can find online?

duplode
  • 31,361
  • 7
  • 69
  • 130
bbnn
  • 3,114
  • 8
  • 46
  • 64

2 Answers2

12

Using scipy.optimize.fixed_point:

import scipy.optimize as optimize

def func(x):
    return -x**3+1

# This finds the value of x such that func(x) = x, that is, where
# -x**3 + 1 = x
print(optimize.fixed_point(func,0))
# 0.682327803828

The Python code defining fixed_point is in scipy/optimize/minpack.py. The exact location depends on where scipy is installed. You can find that out by typing

In [63]: import scipy.optimize

In [64]: scipy.optimize
Out[64]: <module 'scipy.optimize' from '/usr/lib/python2.6/dist-packages/scipy/optimize/__init__.pyc'>

The current fixed_point source code can be found online by going to the documentation page and clicking the [source] link.

unutbu
  • 711,858
  • 148
  • 1,594
  • 1,547
  • 1
    Be warned if you pan to use the code snippet from this answer; the scipy 0.7.0 code for the scalar case contained a bug. The line `if relerr < xtol:` should be `abs(relerr) < xtol` – Len Blokken Oct 02 '18 at 09:55
  • @LenBlokken: Thanks for the heads-up. – unutbu Oct 02 '18 at 11:55
2

Try the SymPy library. Here's a relevant example:

>>> solve(x**3 + 2*x**2 + 4*x + 8, x)
[-2*I, 2*I, -2]

I'm not sure which algorithm SymPy uses to solve the equation, though.

Eli Bendersky
  • 231,995
  • 78
  • 333
  • 394