MATLAB: I want to find points of intersection between the two graphs “cos(x)” and “sqrt(x)-3”. But the command “solve” gives the wrong answer. Why

solve

clc;
clear;
syms x;
y1=@(x)cos(x);
y2=@(x)(sqrt(x)-3);
y = @(x)(y1(x)-y2(x));
fplot (cos(x)-sqrt(x)+3, [0 20]);
k = solve(y(x));
disp(k);

Best Answer

Ugh. A long mess of code to do a simple thing.
syms x
solve(cos(x) == sqrt(x)-3)
Warning: Cannot solve symbolically. Returning a numeric approximation instead.
> In solve (line 304)
ans =
8.0223935834396214239776231141955
I would point out that the solution you were given is indeed a valid solution to the problem. Just not the only one.
vpasolve(cos(x) == sqrt(x)-3)
ans =
- 227.9539774657319103416485656334 + 3.4266780336732822094930660858022i
vpasolve(cos(x) == sqrt(x)-3,10)
ans =
13.413152875945154305531161535157
vpasolve(cos(x) == sqrt(x)-3,7)
ans =
8.0223935834396214239776231141955
As you see, different starting values yield different solutions.
ezplot(cos(x) - (sqrt(x)-3),[0 20])
grid on
If you like one solution more than the others, you need to get the solver started near that point.
So, why did you get a complex solution? That complex solution is perfectly valid. But why? Because I think the default start point for vpasolve is 0. Since there is no analytical solution to this problem, solve gives up, then calls vpasolve, with the default start point. Vpasolve then wanders into the complex plane, finding a solution with an imaginary part.
That plot suggests there is a likely complex root with a real part near 3. We can verify that fact, by starting vpasolve there, but in the complex plane.
vpasolve(cos(x) == sqrt(x)-3,3+i)
ans =
3.3987988860530503671614928946869 + 0.60441771069404813998376706865227i