On Mon, 3 Jul 2023 at 00:16, David Bailey <d...@dbailey.co.uk> wrote:
>
> On 02/07/2023 23:44, Oscar Benjamin wrote:
> > On Sun, 2 Jul 2023 at 23:06, David Bailey <d...@dbailey.co.uk> 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!

Agreed but that means that you need to avoid creating floats in the
first place. Many users find it awkward to do this and prefer to use
nsimplify.

Another option is to call S with a string::

In [27]: s = '1 + x*(m + 1/2)/(2*m + 1) + x**2*(m + 1/2)*(m +
3/2)/(2*(2*m + 1)*(2*m + 2))'

In [28]: print(S(s))
x**2*(m + 1/2)*(m + 3/2)/((2*m + 2)*(4*m + 2)) + x*(m + 1/2)/(2*m + 1) + 1

--
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 sympy+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/sympy/CAHVvXxT4LpkgZfdiKrvzxxENB24cRKUUx88ZLeBKp8ZZwsKJhA%40mail.gmail.com.

Reply via email to