001package de.hdm_stuttgart.sd1.math; 002 003/** 004 * <p>Subset of functions from class {@link java.lang.Math} using power series expansions.</p> 005 * 006 */ 007public class Math { 008 009 static int seriesLimit = 5; 010 011 /** 012 * 013 * @param seriesLimit The last term's index of a power series to be included. 014 * 015 */ 016 public static void setSeriesLimit(int seriesLimit) { 017 Math.seriesLimit = seriesLimit; 018 } 019 020 /** 021 * <p>Approximating the natural exponential function by a finite 022 * number of terms using power series expansion.</p> 023 * 024 * \[ \begin{aligned} 025 * e^x ={} & 1 + {x\over 1!} + {x^2\over 2!} + {x^3\over 3!} + \dots \\ 026 * ={} & \sum_{i = 0}^\infty {x^i\over i!} 027 * \end{aligned} \] 028 * 029 * A power series implementation has to be finite since an 030 * infinite number of terms requires infinite execution time. 031 * 032 * The number of terms to be considered can be set by {@link #setSeriesLimit(int)}} 033 * 034 * @param x The exponential's argument as in \( e^x \) 035 036 * @return The value \( e^x \) itself. 037 */ 038 public static double exp(double x) { 039 double currentTerm = 1., // the first (i == 0) term x^0/0! 040 sum = currentTerm; // initialize to the power series' first term 041 042 for (int i = 1; i <= seriesLimit; i++) { // i = 0 has already been completed. 043 currentTerm *= x / i; 044 sum += currentTerm; 045 } 046 return sum; 047 } 048}