# getting a float result from solve

I am trying to solve a system of 2eqs, and sage keeps giving me integer results. When I try to print a.n() I get an error cannot evaluate symbolic expression numerically.

Sorry, I tried to attach an image of it and I messed it up. Here is the code:

a,b=var('a b')
solve([7.0==a*sqrt(16)/(1+b/16.0),22==a*sqrt(4)/(1+b/4)],a,b)
print a.n()


The result the solve command gives is the ratios of integers.

(I typed an asterisk between the a and the sqrt, but it doesn't show up...)

edit retag close merge delete

1

( 2019-09-02 17:26:15 +0100 )edit
1

I added the complements you put in an answer into the question.

( 2019-09-02 19:06:49 +0100 )edit

Sort by ยป oldest newest most voted

When you run the solve command, the function returns a list of expressions, that are equalities. It does not touch the Python variables a and b which continue to point to the symbols a and b. Those are symbols, not numbers, so it is normal that they do not have any numerical value.

How to extract the values provided by the solve function ?

The simplest way, is first to return the solutions as dictionaries, not as symbolic equalities, by using the solution_dict=True option:

sage: s = solve([7.0==a*sqrt(16)/(1+b/16.0),22==a*sqrt(4)/(1+b/4)],a,b, solution_dict=True)
sage: s
[{b: -592/169, a: 231/169}]


Here, you see that there is only one solution:

sage: s[0]
{b: -592/169, a: 231/169}


You can extract the value for a as follows:

sage: s[0][a]
231/169


and take its numerical value:

sage: s[0][a].n()
1.36686390532544

more

1) When you type code, mark it as such by selecting it and using the "1 0 1 0 1 0" button of the damn' editor...

2) the following one-liner does what you want:

[[u.lhs()==u.rhs().n() for u in S] for S in solve([7.0==a*sqrt(16)/(1+b/16.0),22==a*sqrt(4)/(1+b/4)],a,b)]
[[a == 1.36686390532544, b == -3.50295857988166]]


3) I seriously question the need to get floats (i. e. inexact values). I'd try to keep exact values as far as possible (including in the equations):

sage: solve([7==a*sqrt(16)/(1+b/16),22==a*sqrt(4)/(1+b/4)],a,b)
[[a == (231/169), b == (-592/169)]]


EDIT: I didn't see tmonteil's excellent answer, which was more or less simultaneous. It differs fro mine, but is better on certain aspects(use of solution dictionaries...).

more

Sorry, I tried to attach an image of it and I messed it up. Here is the code: a,b=var('a b')

solve([7.0==asqrt(16)/(1+b/16.0),22==asqrt(4)/(1+b/4)],a,b)

print a.n()

The result the solve command gives is the ratios of integers.

(I typed an asterisk between the a and the sqrt, but it doesn't show up...)

more