For the university course in numerical analysis, we are moving from Maple to a combination of Numpy and Sympy for various illustrations of the course material. This is because students have already learned Python in the semester before.
One of the difficulties we have is to emulate fixed precision in Python. Maple allows the user to specify decimal precision (for example, 10 or 20 digits), and from now on, each calculation is done with such precision that you can see the effect of rounding errors. In Python, we tried to do several ways:
- Sympy has the function of rounding to the specified number of digits.
- Mpmath supports custom precision.
This, however, is not what we are looking for. These parameters calculate the exact result and round the exact result to the specified number of digits. We are looking for a solution that performs each intermediate calculation with a given accuracy. Something that can show, for example, rounding errors that can occur when dividing two very small numbers.
The best solution seems to be a custom data type in Numpy. Using float16, float32, and float64, we could at least give an indication of what might go wrong. The problem here is that we always need to use arrays of one element and that we are limited to these three data types.
Is there something more flexible for our purpose? Or is this what we are looking for hidden somewhere in the mpmath documentation? Of course, workarounds wrap each element of the calculation in a rounding function, but this hides the code for students.
source share