2
$\begingroup$

Given some function I want to find a root around some value $x=x_0$ so I use FindRoot, for example:

root = FindRoot[Exp[x]+Sin[x],{x,0}]

But I want the root to be a number such that:

root = -0.588533

but instead I recieve strange object given by:

{x -> -0.588533}

how to transform it to a number?

$\endgroup$

3 Answers 3

6
$\begingroup$

Some possibilities:

1. ReplaceAll

  x /. root

-0.588533

2. Values

First @ Values @ root

-0.588533

3. Part

root[[1, 2]]

-0.588533

4. Output structure

In many situations the "strange object" is very useful, for example:

Exp[x] + Sin[x] /. root
$\endgroup$
2
  • $\begingroup$ very nicely done. minor thing: isn't this Values @@ root a bit cleaner? $\endgroup$
    – bmf
    Dec 5, 2023 at 8:07
  • 1
    $\begingroup$ Yes, thank you, I overlooked this posssibility $\endgroup$
    – eldo
    Dec 5, 2023 at 8:31
5
$\begingroup$

Less of a solution, more of a comment: Solve and SolveValues are much more powerful than FindRoot and return a Root object that can be treated as an exact number. For example,

s = SolveValues[{Exp[x] + Sin[x] == 0, -1 < x < 0}, x] // First
(*    Root[{E^# + Sin[#]& , -0.589...}]    *)

is the exact number that satisfies the original equation:

Exp[s] + Sin[s] // FullSimplify
(*    0    *)

is exactly zero, not up to numerical accuracy. You can also evaluate s numerically to arbitrary precision:

N[s, 100]
(*    -0.5885327439818610774324520457029036885312715161090305333199142995116725533073514277385240615760274096    *)
$\endgroup$
1
$\begingroup$
$Version

(* "13.3.1 for Mac OS X ARM (64-bit) (July 24, 2023)" *)

Clear["Global`*"]

Solve can provide multiple solutions.

s = Solve[{Exp[x] + Sin[x] == 0, -15 < x < 3}, x]

enter image description here

Verifying the solutions:

Exp[x] + Sin[x] /. s // FullSimplify

(* {0, 0, 0, 0, 0} *)

The roots are exact. Their approximate numeric values are

s // N

(* {{x -> -12.5664}, {x -> -9.4247}, {x -> -6.28505}, {x -> -3.09636}, 
  {x -> -0.588533}} *)

Plot[Exp[x] + Sin[x], {x, -15, 3},
 Epilog -> {Red, AbsolutePointSize[5], Point[{x, 0} /. s]}]

enter image description here

FindRoot requires a different initial value for each of the different roots.

s2 = FindRoot[Exp[x] + Sin[x], {x, #}] & /@ {-13, -9, -6, -3, -1}

(* {{x -> -12.5664}, {x -> -9.4247}, {x -> -6.28505}, {x -> -3.09636}, 
  {x -> -0.588533}} *)

FindRoot is less accurate than Solve

Exp[x] + Sin[x] /. s2

(* {-7.14142*10^-17, 7.1514*10^-16, -1.42681*10^-16, 1.04083*10^-16, 0.} *)
$\endgroup$

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