pythonbeginner - 1 month ago 7
Python Question

python fsolve float object not iterable

I want to use fsolve to solve for alpha and beta (from the Beta distribution)

import numpy as np
from scipy.optimize import fsolve

def mean_and_var(mu,sigma):
a, b = mu,*sigma
return (a/(a+b), a*b/(((a+b)**2)*(a+b+1)))

args = (.5,.05) #mean and variance
alpha,beta = fsolve( mean_and_var, 0, args )

#print (mean_and_var((a, b)))

This shoots me the error

TypeError: 'float' object is not iterable

When using fsolve you must modify the original equation to another one that has the form f(x)=0, in your case:

mu=a/(a+b)
sigma=(ab)/((a+b)^2(a+b+1))

It becomes:

mu - a/(a+b) = 0
sigma - a*b/(((a+b)**2)*(a+b+1)) = 0

n the function that we pass the first parameter is the variable that one wants to find (a, b), and the second the other parameters (mu, sigma).

def mean_and_var(x, *args):
a, b = x
mu, sigma = args
eq1 = mu - a/(a+b)
eq2 = sigma - a*b/(((a+b)**2)*(a+b+1))
return eq1, eq2

args = (.5,.05)
a, b = fsolve(mean_and_var, (.1, .1), args=args)
print("solution: {}, {}".format(a, b))
print("eval in function: {}".format(mean_and_var((a, b), *args)))

output:

solution: 1.9999999999999376, 2.000000000000059
eval in function: (1.5154544286133387e-14, -4.163336342344337e-17)