1

I am trying to use scipy.optimize.fsolve to work out the x-intercept(s):

from scipy.optimize import fsolve
from numpy import array, empty

counter = 0


def f(x_):
    global counter
    counter += 1
    return pow(x_, 3) * 3 - 9.5 * pow(x_, 2) + 10 * x_


x0_ = empty(2)
x0_[0] = 1
x0_[1] = 6
res = fsolve(f, x0=x0_)
print(counter)
print(res)

the function f(x): https://www.desmos.com/calculator/8j8djr01da the result of this code is:

74
[0. 0.]

I expect the result to be

[0, 1.575, 3.175]

Can someone please offer some help.

Plus: I can't understand the documentation of fsolve(x0), is that just a guess? I will be so appreciated if you can explain.

Plus Plus: I will be working with lots of linear equations with unknown expressions and exponential, I am really looking for a way to work out the x-intercepts, in other words, the roots by the expression of f(x).I would be so glad if you can help.

2 Answers 2

3

You get the set of all roots for a polynomial by

numpy.roots([3, -9.5, +10, 0])
array([1.58333333+0.90905934j, 1.58333333-0.90905934j,
   0.        +0.j        ])

It is not clear what your other expected real roots are, fsolve will only find the real root 0.

Of course, if you take the coefficients that you used in the Desmos graphing tool

numpy.roots([2, -9.5, +10, 0])

you will actually get the expected

array([3.17539053, 1.57460947, 0.        ])

For scalar non-polynomial functions the interface scipy.optimize.find_root is perhaps more suitable, especially if you can provide a bracketing interval.

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

Comments

1

I just want to say that at the first step you define your function wrong: it should be

def f(x_):
  #  global counter
  #  counter += 1
    return pow(x_, 3) * 2 - 9.5 * pow(x_, 2) + 10 * x_

but notpow(x_, 3) * 3 - 9.5 * pow(x_, 2) + 10 * x_

If you then set x0_ precisely:

x0_=[0,1,3] # according to intersection on graph
res=fsolve(f, x0=x0_)

Give you the anticipated output:

[0.         1.57460947 3.17539053]

Sometimes you just have to be more careful :)

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.