I need to compute some automatically generated expressions, which may contain square roots, with the class Zmod.
For example, I want to evaluate the following expression modulo 9 (thus, using the class Zmod(9)):
expr = "-1 / sqrt(7) + 5"
In the above case, I want to get the results 7 (for sqrt(7) = 4) and 3 (for sqrt(7) = 5).
Is this possible with Sage? How can I get these results? If I need to use another library, which one should I use and how?
I thank you in advance for your answers!
Elements of
Zmodhave an.sqrt()method, but you can also pass them to thesqrtfunction. Example:If you want to automatically parse a string expression like
"-1 / sqrt(7) + 5"and convert all numeric constants to elements ofZmod(9), I'd suggest to use Sage's symbolic ringSRas a parser, and then traverse the expression tree using the.operator()and.operands()methods in a recursive function. Like so:This would probably handle most expressions you may have. If you want both results depending on the sign choice for the square root, then modify
zmod_evalto return a list, and handle the sqrt operation specially. Unfortunately, Sage's symbolic ring handles sqrt as a generic power:so if your expression also contains integer powers you will have a difficult time distinguishing between them and the square root.
Ultimately, I'd think it's simpler to modify your expression generator to output
Zmod(9)wherever is needed, rather than trying to play around with Sage.