Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

answered 2011-01-24 16:31:53 -0600

DSM gravatar image

You only mention cos, but presumably there are other things you're going to want to do with your angles: sin, tan, add them, subtract them, convert them to floats, possibly simplify them, and so on. That's a lot of hassle to implement, so instead let's subclass the built-in Expression class and let it do most of the work.

class FixedValue(Expression):
    def __init__(self, value):
        Expression.__init__(self, SR, value)
    def new_method(self, *args):
        print self, args

sage: x = FixedValue(pi/2)
sage: x
1/2*pi
sage: cos(x), sin(x), tan(x)
(0, 1, Infinity)
sage: float(x), complex(x)
(1.5707963267948966, (1.5707963267948966+0j))
sage: RealField(200)(x)
1.5707963267948966192313216916397514420985846996875529104875
sage: ComplexField(64)(x+2j)
1.57079632679489662 + 2.00000000000000000*I
sage: x+x, x*3
(pi, 3/2*pi)
sage: simplify(exp(x*I))
I
sage: x.new_method(99, 'fred')
1/2*pi (99, 'fred')

Note that the above doesn't store a copy of its value in ".value"; you can simply refer to the object itself. If you do store a copy you have to worry about them getting out of sync.

You only mention cos, but presumably there are other things you're going to want to do with your angles: sin, tan, add them, subtract them, convert them to floats, possibly simplify them, and so on. That's a lot of hassle to implement, so instead let's subclass the built-in Expression class and let it do most of the work.

class FixedValue(Expression):
    def __init__(self, value):
        Expression.__init__(self, SR, value)
    def new_method(self, *args):
        print self, args

sage: x = FixedValue(pi/2)
sage: x
1/2*pi
sage: cos(x), sin(x), tan(x)
tan(x), float(x), complex(x)
(0, 1, Infinity)
sage: float(x), complex(x)
(1.5707963267948966, Infinity, 1.5707963267948966, (1.5707963267948966+0j))
sage: RealField(200)(x)
1.5707963267948966192313216916397514420985846996875529104875
sage: ComplexField(64)(x+2j)
1.57079632679489662 + 2.00000000000000000*I
sage: x+x, x*3
x*3, simplify(exp(x*I))
(pi, 3/2*pi)
sage: simplify(exp(x*I))
I
3/2*pi, I)
sage: x.new_method(99, 'fred')
1/2*pi (99, 'fred')

Note that the above doesn't store a copy of its value in ".value"; you can simply refer to the object itself. If you do store a copy you have to worry about them getting out of sync.sync. Also note that while the above makes it easy to operate on these objects, the result of an operation won't be an instance of the class (e.g. x*1 is an Expression, not a FixedValue), but you can easily coerce back, or we can work around it if necessary.