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 https://docs.sympy.org/latest/modules/simplify/simplify.html#sympy.simplify.simplify.nsimplify I normally use sympy through the command line isympy interface which is a wrapper around ipython that provides an environment automatically set up for using sympy. I don't use this myself but isympy has a -i flag to interpret integer literals as sympy Integers (and therefore integer division as rational division): $ isympy -i ... In [1]: 1/3 Out[1]: 1/3 In [2]: print(1 + x*(m + 1/2)/(2*m + 1) + x**2*(m + 1/2)*(m + 3/2)/(2*(2*m + 1)*(2*m + 2))) x**2*(m + 1/2)*(m + 3/2)/((2*m + 2)*(4*m + 2)) + x*(m + 1/2)/(2*m + 1) + 1 I think that previous versions of SymPy Live would reinterpret 1/3 as rational division in a similar way but that does not seem to be true of the current version (maybe that was missed in the move to pyodide): https://live.sympy.org/ -- Oscar -- 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/CAHVvXxSJsXvaG28ZgUWp2YrL70Dykzu8dDQ3gqoBs9sn%3DhyKzQ%40mail.gmail.com.
