Ask Your Question

Revision history [back]

You defined e1 as an expression involving x:

sage: e1 = x^3 + 4*x - 7

You can plot it directly as a function of x:

sage: plot(e1, (x,-15,15), ymin=-15, ymax=15)

You solved the expression for x (you could shorten your code):

sage: ans = solve(e1, x)
sage: print(ans)

You get three solutions, two complex conjugate and one real. Since you started from a degree three polynomial with integer coefficients, Sage was able to find the roots algebraically (with square roots and cube roots, see Roots of a cubic function).

Exact formulas are nice, but now how do we get a numerical value?

You can get hold of the last solution like this:

sage: a = ans[2].rhs()

and substitute it in your expression to check that the expression becomes zero there.

sage: e1.subs(x=a)

This gives you a messy expression, because all the cube roots and square roots need to be simplified, which Sage does not do automatically.

You could ask for a numerical value of the expression evaluated at this value.

sage: e1.subs(x=a).n()
-1.33226762955019e-15

It's very close to zero (roughly 1.33 * 10^-15) but not exactly zero, because the approximations involved in taking numerical values did not cancel out perfectly.

You could ask sage to simplify the messy algebraic expression, which in this case works.

sage: e1.subs(x=a).full_simplify()
0

Now let's get a numerical value of the real root.

sage: a.n()
1.25538315684475

To check again, you can substitute this numerical value into the expression and see that it is zero up to the displayed precision.

sage: e1.subs(x=a.n())
0.000000000000000

Of course, if you were only interested in the numerical value, you could have used a numerical method, as mentioned in calc314's answer. Since the graph lets you see the root is between 1 and 2, you can specify these bounds.

sage: find_root(e1,1,2)
1.255383156844765