MATLAB: The own function is not working with 3x^2-12-15=0

equation solverquadratic

Hi there, I tested my function with some equations but it failed with 3x^2-12-15=0. It is expected x=5,-1 but it returns x=45,-9. here is the screen shot of my function with prompt test.

Best Answer

First, verify that your solution is correct.
roots([3 -12 -15])
ans =
5
-1
Homework is good. Learn to write MATLAB, as well as learning the quadratic formula. But also learn that the solution has been written for you, and written well, by experts in the field. So normally, just use roots. You can also use solve, as Birdman points out.
If I take your code, writing it like this (since all you posted was a picture, so I will need to retype it myself.)
x1 = (-b + sqrt(b^2 - 4*a*c))/2*a
x2 = (-b - sqrt(b^2 - 4*a*c))/2*a
we WILL GET THE WRONG ANSWERS. Why? The correct way to write it was:
x1 = (-b + sqrt(b^2 - 4*a*c))/(2*a)
x2 = (-b - sqrt(b^2 - 4*a*c))/(2*a)
The difference is entirely in a necessary set of parens around the denominator. For example...
6/2*3
ans =
9
Yet,
6/(2*3)
ans =
1
There is a difference, and it is important. :)