Ask Your Question
1

scipy.optimize.newton gives TypeError: ufunc 'isfinite' not supported

asked 2021-12-11 20:23:38 +0200

ttdsmt gravatar image

updated 2021-12-17 15:31:03 +0200

Here is the code

import scipy.optimize
f(x) = x^2 - 4*sin(x)
fp(x) = diff(f(x),x)
scipy.optimize.newton(f,1.5,fp)

and get type error

TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

How to solve this error?

Some other information:

Run in Sagemath 9.4 on Cocalc.com

This code from the book "Numerical Analysis Using Sage by George A. Anastassiou, Razvan A. Mezei" which use "Sage Version 6.3, Release Date: 2014-08-10". Here, I edited the origin code (removing comment, and print command), the original code is:

#import the following library
import scipy.optimize
#the function f(x) from our problem
f(x) = x^2-4*sin(x)
#compute the derivative of f
fp(x)=diff(f(x),x)
#call the Newton’s method and output the result
print "solution = " , scipy.optimize.newton(f, 1.5, fp)

An extra question, is this code work on the old version of Sage in the above book, i.e. "Sage Version 6.3, Release Date: 2014-08-10"?

edit retag flag offensive close merge delete

Comments

Welcome to Ask Sage! Thank you for your question.

slelievre gravatar imageslelievre ( 2021-12-12 04:28:08 +0200 )edit

You can also define Python function to the same effect :

sage: def f(x): return x^2-4*sin(x)
sage: def fp(x): return 2*x-4*cos(x)
sage: import scipy.optimize
sage: scipy.optimize.newton(f,1.5,fp)
1.93375376282702

see Sagecell...

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2021-12-18 11:30:08 +0200 )edit

1 Answer

Sort by » oldest newest most voted
3

answered 2021-12-18 02:16:08 +0200

tmonteil gravatar image

scipy.optimize.newton is numerical and requires f and fp to be callable, so a simple way to solve the issue is to transform f and fp into numerical callable functions with the fast_callable function :

sage: scipy.optimize.newton(fast_callable(f),1.5,fast_callable(fp))
1.93375376282702
edit flag offensive delete link more

Comments

You can also define f and fp as Python functions : see Sagecell...

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2021-12-18 11:31:37 +0200 )edit

The problem with that code is that you can not deduce fp from f since a Python function has no such thing as "a derivative".

tmonteil gravatar imagetmonteil ( 2021-12-18 22:39:42 +0200 )edit

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

Stats

Asked: 2021-12-11 20:23:38 +0200

Seen: 599 times

Last updated: Dec 18 '21