On 02/07/2023 23:44, Oscar Benjamin wrote:
On Sun, 2 Jul 2023 at 23:06, David Bailey <[email protected]> wrote:
Dear Group,
If I want to enter m+1/2, I define m as a symbol and write:
m+S(1)/2.
However if I have a complicated expression with lots of fractions, such as:
1 + x*(m + 1/2)/(2*m + 1) + x**2*(m + 1/2)*(m + 3/2)/(2*(2*m + 1)*(2*m + 2))
it would be much neater if I could automatically wrap all the integers
in S so that no floating point numbers get introduced.
Is that feasible? I did try wrapping the whole expression in S, but that
does not work.
You can wrap the whole expression in nsimplify:
>>> e = 1 + x*(m + 1/2)/(2*m + 1) + x**2*(m + 1/2)*(m + 3/2)/(2*(2*m
+ 1)*(2*m + 2))
>>> print(e)
x**2*(m + 0.5)*(m + 1.5)/((2*m + 2)*(4*m + 2)) + x*(m + 0.5)/(2*m + 1) + 1
>>> print(nsimplify(e))
x**2*(m + 1/2)*(m + 3/2)/((2*m + 2)*(4*m + 2)) + x*(m + 1/2)/(2*m + 1) + 1
The nsimplify function will attempt to guess what rational number a
float represents. In your example this is easy because all floats are
exactly represented in binary (having only twos in the denominator)
but otherwise the conversion can be inexact:
>>> f = 1/3
>>> f
0.3333333333333333
>>> print(Rational(f)) # exact value of the binary float
6004799503160661/18014398509481984
>>> nsimplify(f) # probably the value that the float was intended to have
1/3
Thanks Oscar for that incredibly fast reply, but I'm not super keen on
algebra that is only probably correct!
David
--
You received this message because you are subscribed to the Google Groups
"sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/sympy/ac6fb0b7-cb06-565a-9522-ce602eefa5a5%40dbailey.co.uk.