user3646248
user3646248

Reputation: 73

fsolve on python (converting matlab code to python code)

I have one program on matlab but i want to convert in python, my matlab code is :

function [f]=equation1(x)
%options = optimoptions('fsolve','TolFun',1.1e-20,'TolX',1.1e-20,'maxIter',Inf,'MaxFunEvals',Inf);
c = 330 ;%speed of sound meters per second 
% unknown variable : 
% r1 => x(1) 
% theta => x(2)

time2 = 0.455; % Microphone 1 to Microphone 2 time delay
time3 = 0.606; % Microphone 1 to Microphone 3 time delay
% gives : 
r2 = 150 %time2*c;
r3 = 200 %time3*c; 

r4 = 499.1; % Distance from Microphone 2 to Microphone 3
r5 = 1267.9;% Distance from Microphone 1 to Microphone 3

phi = 16.177; % Angle between Microphone 1 and Microphone 2 measured from Microphone 3
 %
f(1)= (x(1) + r2)^2- (x(1)+r3)^2 -r4^2 +2*(x(1)+r3)*r4*cosd(x(2));
f(2)= x(1)^2  - (x(1)+r3)^2  - r5^2 + 2*(x(1)+r3)*r5*cosd(x(2)-phi);

Iplay this code with [x,feval]=fsolve(@equation1,[100 10]); he return good value ( 1620.7 076.4) But on python I have make this program

from scipy.optimize import fsolve
import math

def  cosd(x):
    return math.cos(x * math.pi / 180);


def equations(p):
    time2 = 0.455 # Microphone 1 to Microphone 2 time delay
    time3 = 0.606 # Microphone 1 to Microphone 3 time delay
    # gives : 
    r2 = 150. #time2*c;
    r3 = 200. #time3*c; 

    r4 = 499.1  # Distance from Microphone 2 to Microphone 3
    r5 = 1267.9 # Distance from Microphone 1 to Microphone 3

    phi = 16.177 # Angle between Microphone 1 and Microphone 2 measured from Microphone 3
        r1, theta = p
    f1 = (r1 + r2)**2. -(r1+r3)**2 -r4**2 +2*(r1+r3)*r4*(cosd(theta))
    f2 = r1**2  - (r1+r3)**2  - r5**2 + 2*(theta+r3)*r5*(cosd(theta-phi))
        return (f1,f2)

x, y =  fsolve(equations, (1000.0, 20.0), xtol=1e-06, maxfev=10000000)

print x,y, equations((x, y))

But when i run, i have a bad value with this error :

The iteration is not making good progress, as measured by the improvement from the last five Jacobian evaluations. warnings.warn(msg, RuntimeWarning) (-167792.68841940007, -1096453.7938717711)

Anyone say why it doesn't work on python ?

EDIT => I change the python code for problem in degree. But I don't have the good value, (python return -4263.77780373 -272.257364385, it's far from the matlab value).

Upvotes: 5

Views: 1312

Answers (2)

user3646248
user3646248

Reputation: 73

Thank you, I have found my error (with your help)

  • one for the cosinus, i have solve with this function :

    def cosd(x): return math.cos(x * math.pi / 180);

    • And the other I have invert r1 by theta in

f2 = r1**2 - (r1+r3)**2 - (r5)**2 + 2*(r1+r3)r5(cosd(theta-phi))

Upvotes: 0

FuRioN
FuRioN

Reputation: 633

I think the problem is this subtraction:

(theta-phi)

In matlab you are subtracting degrees but on python theta is in dregrees and phi is in radiands.

Upvotes: 3

Related Questions