Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I override the __str__ method of sympy.core.numbers.Float?

Tags:

I am trying to overcome the flaws of sub-classing Python's float by using a different class hierarchy of numbers. However the following code:

from sympy import *
import sympy.core.numbers

f = 1.123456789
n = N(f, 8)

print n
print type(n)

sympy.core.numbers.Float.__str__ = lambda f: "{:.8f}".format(f)

print n

yields the error:

AttributeError: 'module' object has no attribute 'numbers'

How can I overcome this?

like image 707
Terrence Brannon Avatar asked Apr 11 '17 03:04

Terrence Brannon


1 Answers

This does what you need:

Code:

from sympy.core.numbers import Float
Float.__str__ = lambda f: "{:.8f}".format(float(f))

Test Code:

from sympy import N
from sympy.core.numbers import Float

f = 1.123456789
n = N(f, 8)

Float.__str__ = lambda f: "{:.8f}".format(float(f))

print n

Results:

1.12345679
like image 163
Stephen Rauch Avatar answered Sep 23 '22 09:09

Stephen Rauch