我正在测试MATLAB功能,以解决我打算做的项目的方程式,所以我给了它一个简单的测试运行,但它给我的结果是不正确的。我试图解决两个带有两个未知数的非线性方程,其中一个解是正确的,另一个不是。
syms theta d x y
eq1 = d * cos(theta) == x;
eq2 = d * sin(theta) == y;
sol = solve(eq1, eq2, theta, d)
sol.theta
sol.d
d的解决方案是正确的,但对于theta我得到:
-2*atan((x - (x^2 + y^2)^(1/2))/y)
-2*atan((x + (x^2 + y^2)^(1/2))/y)
对theta的正确答案就是atan(y / x)
然后,当我用x = 1,y = 0评估这些解决方案时,我得到:
eval(sol.d)
eval(sol.theta)
d = 1, -1
theta = NaN, -3.1416
d的解决方案是正确的,但那个场景中的theta应该是0.我做错了什么?
编辑:手工解决它看起来像这样:用x等式划分y等式
y/x = (d * sin(theta)) / (d * cos(theta))
y/x = sin(theta)/cos(theta)
y/x = tan(theta)
theta = atan(y/x)
即使matlab以其他方式解决它并得到不同的表达式,当我使用数字时它应该仍然产生相同的最终结果,而它总是如此。
对于x = 1和y = 0,θ应为0,=>这不起作用,它给出NaN(下面的解释)
对于x = 1和y = 1,theta应该是45度=>这是有效的
对于x = 0和y = 1 theta应该是90度=>这是有效的
我只是用x和y的45度和90度值再次检查它并且它可以工作,但是对于x = 1和y = 0,它仍然将NaN作为答案之一,这是因为它得到了0/0表达它的方式
-2*atan((x - (x^2 + y^2)^(1/2))/y)
-2*(1 - (1^2 + 0^2))^(1/2)/0
-2*(1 - 1)^(1/2)/0
0/0
但如果它以atan(y / x)的形式出现,结果是
theta = atan(0/1)
theta = atan(0)
theta = 0
你的意思是解决这个问题:
syms a b theta d real
eq1 = a==d * cos(theta) ;
eq2 = b==d * sin(theta) ;
[sol] = solve([eq1 eq2],[d theta] ,'IgnoreAnalyticConstraints', true,'Real',true,'ReturnConditions',true);
当使用符号x
和y
求解方程时,求解器将找到具有特定条件的解,可以使用参数'ReturnCondition'
获得:
syms x y theta d real
eq1 = d*cos(theta) == x;
eq2 = d*sin(theta) == y;
sol = solve([eq1; eq2],[d theta],'ReturnConditions',true);
这为sol
提供了以下结果
>> sol.d
(x^2 + y^2)^(1/2)
-(x^2 + y^2)^(1/2)
>> sol.theta
2*pi*k - 2*atan((x - (x^2 + y^2)^(1/2))/y)
2*pi*k - 2*atan((x + (x^2 + y^2)^(1/2))/y)
>> sol.parameters
k
>> sol.conditions
y ~= 0 & in(k, 'integer')
y ~= 0 & in(k, 'integer')
如您所见,y = 0不满足求解器给出的这种通用解,导致y = 0的问题。您可以通过使y
数字而不是符号来找到y = 0的解,或者通过添加假设:
syms x y theta d real
assume(y==0)
sol = solve([eq1; eq2],[d theta],'ReturnConditions',true);
我想在这一个条件下设置y = 0数字更容易,因为上面三条线路已经有4种可能的解决方案和条件。