Mason Hargrave
Mason Hargrave

Reputation: 3

How to fix TypeError when using `scipy.optimize.fsolve`?

I am trying to find the roots of a function F(f) while varrying the values of a parameter x by using scipy.optimize.fsolve. Here is the code:

from scipy.optimize import fsolve
import numpy as np

def F(f,*x):
    return np.cosh(((x-1)/(x+1))*(np.log(2)/f))-0.5*np.exp(np.log(2)/f)

x = np.logspace(0,3,100)
y = np.arange(x.size)

for i in range(x.size):
    y = fsolve(F, 0.5, args = x[i])

The code above returns a:

TypeError: unsupported operand type(s) for -: 'tuple' and 'int'

The funny thing is that this same code works when I change F(f,x) to a simple function, there is no TypeError

def F(f,*x):
   return (2*np.cos(f)-f)*x

x = np.logspace(0,3,100)
y = np.arange(x.size)

for i in range(x.size):
    y = fsolver(F, 0.5, args=x[i])

What is it about the first function that causes a type error where as the second function is just fine?

Upvotes: 0

Views: 210

Answers (1)

HzCheng
HzCheng

Reputation: 401

Remove the * in the definition of F.

Since you use variable parameter list *x, the x that F received is actually a tuple, and np.cosh(((x-1)/(x+1))) operation doest not support tuple.

Upvotes: 1

Related Questions