0
votes

I want to find the root (i.e. the value x so that f(x)=0) for a function "func" using the Newton method imported from scipy.optimize. I wrote the following code:

import numpy

from scipy import optimize


def A(b, c, e=70):
    d = 1 - c
    b_prime = ((1 + b) ** 3)
    wurzel = numpy.sqrt(c * b_prime + d)

    return e * wurzel

def U(b, c, e=70):
    return A(b, c, e=70)/e

def func(U, c, b, a):
    return U(b, c, e=70)**2 - (U(b, c, e=70)**a * (1-c)) - (c * (1+b)**3)

def func_prime(U, c, a):
    return 2*U(b, c, e=70) - (a*(U(b, c, e=70)**(a-1)))*(1-c)

def U_0(b, c):
    numpy.sqrt((c * (1+b)**3) + 1 - c )

res = optimize.newton(func(U, c, b, a), U_0(b, c), fprime=func_prime(U, c, a), args=(c, b, a))

I calculated U_0 analytically by assuming a=0 in func and solving for U. I get the follwing error:

Traceback (most recent call last):
  File "root_finding_stack.py", line 25, in <module>
    res = optimize.newton(func(U, c, b, a), U_0(b, c), fprime=func_prime(U, c, a), args=(c, b, a))
NameError: name 'c' is not defined

The error says c is not defined but that's the point, I don't want to definde a,b and c but find U(a,b,c) to root my function. Am I using the wrong method or what am I doing wrong here? Also I am not sure if I pass the 3 arguments correctly in the optimize.newton function

Edit: I added the function in mathematical notation

This is my function f(U,b,c) where U is a function of b and c as well

I am trying to find a U(b,c) that fullfills this equation

1
I don't know scipy, but surely you need to pass .newton a function object, just like you pass U to func. Instead, you're passing the result of the call func(U, c, b, a), which means that .newton would get a float for that arg if the call succeeded. But of course it doesn't succeed, since those args are undefined at the time of the call. - PM 2Ring
Can you give us the function for which you're trying to get a root in ordinary mathematical notation? You could post it in your question as an image. If you do that, let me know. - Bill Bell
I added the mathematical notation - user7248647

1 Answers

1
votes

func is the function to solve. But you have defined a function that as it's first argument, has another function U which is a function of A, b, c (and e but thats constant) and A is also a function.

Newton-Raphson is a one-dimensional solver and so can only find roots of f(x) not f(g(b,c),a,b,c) where a, b, c are all unknown.

It also seems that you are conflating python function definitions and usage with mathematic function definition and usage.