简体   繁体   English

算法二次方程MATLAB

[英]algorithm quadratic equation MATLAB

What condition should I put in code of matlab so that get the exactly solutions of a quadratic with these formulas: 我应该在matlab代码中输入什么条件,以便使用以下公式获得二次方的精确解:

x1=(-2*c)/(b+sqrt(b^2-4*a*c))
x2=(-2*c)/(b-sqrt(b^2-4*a*c))

Directly implementing these formulas I don't get the correct solution in certain cases such x^2-1000001x+1 直接执行这些公式在某些情况下,例如x^2-1000001x+1我得不到正确的解决方案

Thank you very much for your help 非常感谢您的帮助

The correct set of formulas is 正确的公式集是

w = b+sign(b)*sqrt(b^2-4*a*c)

x1 = -w/(2*a)

x2 = -(2*c)/w

where sign(b)=1 if b>=0 and sign(b)=-1 if b<0. 如果b> = 0,则sign(b)= 1;如果b <0,则sign(b)=-1。

Your formulas as well as the standard formulas lead to catastrophic cancellation in one root of b is large wrt. 您的公式以及标准公式都会导致b的一大根发生灾难性的取消。 a and c. a和c。


If you want to go to the extremes, you can also guard against over- and underflow in the computation of the term under the square root. 如果要极端,可以在平方根下的项的计算中防止上溢和下溢。

Let m denote the maximum size of |a|, |b| 令m表示| a |,| b |的最大大小。 and |c|, for instance the maximum of the exponent in their floating point representation, or of their absolute value... Then 和| c |,例如其浮点表示形式中的最大值或它们的绝对值...然后

w = b+sign(b)*m*sqrt( (b/m)*(b/m)-4*(a/m)*(c/m) )

has a term between -10 and 10 below the root. 词根下方有-10到10之间的词。 And if this term is zero, then that is not caused by underflow. 如果该项为零,则不是下溢引起的。

You're dealing with floating point arithmetic in matlab, so exact solutions are not guaranteed. 您正在使用matlab处理浮点算法,因此无法保证确切的解决方案。 (Ie it's possible that every single floating point value will cause round-off error that gives non-zero answer when you plug into your original quadratic equation). (即,当您插入原始的二次方程式时,每个浮点值都有可能导致舍入误差,从而产生非零的答案)。 A better way to check whether you have found a solution to an equation in floating point is to use a tolerance, and check whether the absolute value of your answer is less than the tolerance. 检查是否已找到浮点方程的解的更好方法是使用公差,并检查答案的绝对值是否小于公差。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM