Ask Your Question

Is fast_callable breaking my code?

asked 2023-06-04 18:04:48 +0200

fermiona gravatar image

updated 2023-06-12 20:18:04 +0200

I'm currently trying to make an interact for newton fractals that accepts most functions. This is my code for newton's method:

import numpy as np

def newton(z0,f,fp,MAX_IT):
      cnt = 0
      TOL = 1e-10
      z = z0
      condition = fp(z) != 0
      a = z[condition]
      for i in range(MAX_IT):
           dz = f(a)/fp(a)
           adz = np.absolute(dz)
           if np.all(adz < TOL) :
              return a
           cnt += 1
           a -= dz
      return False


g(a) = sin(a)
f = fast_callable(g, vars=(a))
fp = fast_callable(diff(g), vars(a))
x = np.linspace(-7,7,100)
y = np.linspace(-7,7,100)
xx,yy = np.meshgrid(x,y)


array([-6.28318531+0.j, -6.28318531+0.j, -6.28318531+0.j, ...,
        6.28318531+0.j,  6.28318531+0.j,  6.28318531+0.j])

I'm supposed to get 0 or 2*pi in addition to the above. When I use numpy functions I don't have this issue. Is fast_callable breaking something?

edit retag flag offensive close merge delete




one can obtain the same result

achrzesz gravatar imageachrzesz ( 2023-06-08 12:43:44 +0200 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2023-06-08 07:00:06 +0200

Emmanuel Charpentier gravatar image

updated 2023-06-08 07:02:04 +0200

Your code finds one solution then stops.

To get the other solutions, you shound recursively search solutions in the intervaldefined by the bounds of the original interval and your first solution.

The trick is, of course, to detect when to stop for good... Left to the reader as a ((very) interesting) exercise. Hint : what your function should do when asked to find the roots of $\sin\frac{1}{x}$ between $-\pi$ and $\pi$ ?

BTW, the use of numpy is irrelevant. you might as well use the code fior Newton's method already existing in Sage, using numpy-defined variables and functions.


edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2023-06-04 18:04:48 +0200

Seen: 318 times

Last updated: Jun 12 '23