-1
$\begingroup$

Slove the eqaution 2x^2+5x+1=0 in real number range.

Then, by putting it in the equation, check if that is correct.

(Use NSlove, Chop, and substitution)

I want a code which uses above three operations... help me !

$\endgroup$

2 Answers 2

1
$\begingroup$

Do you need something like this?

eq = 2*z^2 + 5*z + 1;
sol = NSolve[2*x^2 + 5*x + 1 == 0, x, Reals] (*two real solutions*);
eq /. {z -> x /. sol[[1]]} // Chop
eq /. {z -> x /. sol[[2]]} // Chop
$\endgroup$
2
  • 1
    $\begingroup$ hi, I think you can just use Solve for this one. No need to use NSolve. You could always apply N at end to the result to convert exact numbers to machine numbers. It should be more accurate this way. $\endgroup$
    – Nasser
    Commented Apr 3, 2020 at 19:16
  • $\begingroup$ sure, but the post asked that NSolve be used $\endgroup$
    – F.Mark
    Commented Apr 3, 2020 at 22:48
1
$\begingroup$
eqn = 2 x^2 + 5 x + 1 == 0;

The exact solution is

sol = Solve[eqn, x, Reals]

(* {{x -> 1/4 (-5 - Sqrt[17])}, {x -> 1/4 (-5 + Sqrt[17])}} *)

Verifying that both solutions are valid

eqn /. sol

(* {True, True} *)

However, for this particular equation the roots are real and it is not necessary to restrict the domain to get identical (SameQ) results.

sol === Solve[eqn, x]

(* True *)

For approximate numeric results

(soln = NSolve[eqn, x, Reals]) // InputForm

(* {{x -> -2.280776406404415}, 
 {x -> -0.21922359359558485}} *)

Note that these are machine numbers with no known precision. The numeric results are consistent with the exact results.

soln === (sol // N)

(* True *)

However, the verification of the numeric results fails due to a precision issue.

eqn /. soln

(* {False, False} *)

You can use Chop to verify that the LHS of the equation evaluates to approximately zero.

eqn[[1]] /. soln // Chop

(* {0, 0} *)

Alternatively, specifying a WorkingPrecision will resolve this as the equation's Equal test is then done to the precision of the solution.

(soln2 = NSolve[eqn, x, Reals, WorkingPrecision -> 10]) // InputForm

(* {{x -> -2.2807764064044149243670744\
9087407439947`10.}, 
 {x -> -0.2192235935955848535883205\
840946175158`10.}} *)

Note that the above result indicates that the values have a known precision of 10. digits consistent with the specified WorkingPrecision. The result of the equation's Equal test is then

eqn /. soln2

(* {True, True} *)
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.