cachemoi
cachemoi

Reputation: 373

Why can the solve() function in matlab solve this equation while the nsolve() function in sympy requires a guess?

I have a mode, a maximum and minimum value of X (Xmin and Xmax), and a percentage confidence (percentage).

I want to use the following functions in order to find the μ and σ of a theoretical log normal distribution:

The cumulative distribution function:

CDF

and the mode

mode

I began with the following Matlab script:

function [mu, sigma] = DefLog(Mode, Percentage, Xmin, Xmax)

syms s
eqn = 1/2+1/2*erf((log(Xmax)-(log(Mode)+s^2))/(sqrt(2)*s))-(1/2+1/2*erf((log(Xmin)-(log(Mode)+s^2))/(sqrt(2)*s)))==Percentage;
sigma = solve(eqn,s)

mu=log(Mode)+sigma^2

end

And this gives me a single numerical solution for mu and sigma.

For example if I run DefLog(2, 0.95, 1, 4) I get sigma = 0.33 and mu = 0.80

I needed to translate this equation into Python, so I used sympy to solve the same equation. The only way I could get a single numerical solution with sympy was to use the nsolve function. My code is as follows:

from sympy import *

def CalcScaleParamOPT(mode, percentage, Xmin, Xmax):

    s = Symbol('s', Real=True)

    eqn = (1/2+1/2*erf((log(Xmax)-(log(mode)+s**2))/(sqrt(2)*s))-(1/2+1/2*erf((log(Xmin)-(log(mode)+s**2))/(sqrt(2)*s)))) - 0.95

    sigma = nsolve(eqn, 0.6)

    mu=log(mode)+sigma**2

    print(sigma)
    print(mu.evalf())


CalcScaleParamOPT(2, 0.95, 1, 4)

This gives the same solution as the matlab script, but unlike the matlab solve() function nsolve() requires a "guess" close enough to the answer I am looking for. How can matlab find a single solution without the guess?

Upvotes: 2

Views: 411

Answers (1)

asmeurer
asmeurer

Reputation: 91450

Based on the documentation, MATLAB's solve falls back to a numerical solution automatically. Assumedly it generates a guess value automatically (it doesn't mention how), but it does say that you can use vpasolve to pass in a guess interval manually, since the default solve only returns one numerical solution (the first one it finds).

Upvotes: 1

Related Questions