How to get a decimal instead of a fraction in sympy?
Question:
I am making a chemistry project for school, I want to use sympy for solving some density and concentration problems.
solveset
function returns the value as a fraction, for example:
mL = Symbol("mL")
density = Symbol("p")
mass = 115*g
volume = 100*ml
print(solveset(Eq(density, mass/volume), density))
The output is {23*g/(20*mL)}
(fraction) but I want it in the decimal form ({1.15*g/ml}
)
Answers:
You can use the n()
method to evaluate the symbolic results to floats. Note that n
is an alias of the evalf
method. But first, you probably want to extract the result from the set of solutions:
sol = solveset(Eq(density, mass/volume), density)
sol = list(sol)[0].n()
print(sol)
# 1.15*g/mL
I am making a chemistry project for school, I want to use sympy for solving some density and concentration problems.
solveset
function returns the value as a fraction, for example:
mL = Symbol("mL")
density = Symbol("p")
mass = 115*g
volume = 100*ml
print(solveset(Eq(density, mass/volume), density))
The output is {23*g/(20*mL)}
(fraction) but I want it in the decimal form ({1.15*g/ml}
)
You can use the n()
method to evaluate the symbolic results to floats. Note that n
is an alias of the evalf
method. But first, you probably want to extract the result from the set of solutions:
sol = solveset(Eq(density, mass/volume), density)
sol = list(sol)[0].n()
print(sol)
# 1.15*g/mL