Implementing exponentials.
No. 117
The exponential
Q: |
The exponential is being defined by a power series: Equation 1. Power series definition of
Implement a class method Regarding practical calculations we replace the above infinite series by a limited one. So the number of terms to be considered will become a parameter which shall be configurable. Continue the implementation of the following skeleton: Figure 297. An implementation sketch for the exponential
Compare your results using Do not forget to provide suitable Javadoc comments and check the generated HTML documentation for correctness. Hints:
|
||
A: |
Regarding the finite number of terms we provide a class variable ❶ having default value of 5 corresponding to just the first 1 + 5 = 6 terms: We also provide a corresponding setter method ❷ enabling users of our class to choose a different value:
Calculating values by a finite series requires a loop:
You may also view the Javadoc and the implementation of double Math.exp(double). We may use the subsequent code snippet for testing and comparing our implementation:
In comparison with a professional implementation we have the following results: e^1=2.7180555555555554, difference=-2.262729034896438E-4 e^2=7.355555555555555, difference=-0.033500543375095226 e^3=19.412499999999998, difference=-0.67303692318767 Our implementation based on just 6 terms is quite good for small values of x. Larger values however exhibit growing differences. This is due to the fact that our approximation is in fact just a polynomial of degree 6: Figure 298. Comparing exponential and approximation
The plots show a particularly bad approximation for negative values. But for larger values outside the above scope the exponential will quickly diverge from its polynomial approximation as well. |