Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Test {
- /*
- The idea is to write a version of Math.pow(x,y), to find x^y, without
- using any library functions.
- If y is a positive integer, we just do a loop x X x X x.. y times.
- But if y is not an integer?
- We do exp( y log x )
- So we need to write a log function and an exponential
- */
- static double abs(double x)
- { // version of Maths.abs
- return x<0?-x:x;
- }
- static double log(double xx) {
- final double E = 2.7182818284590452353602874713527; // Euler's constant, e
- if (xx < 0) { // no log negative number
- throw new IllegalArgumentException();
- }
- double nn=0; // see later
- if (xx > 1) { // use Maclaurin series for log(1+x)
- while (xx>E) // remove powers of e
- {
- xx/=E;
- nn++; // counting them - we add in nn at the end
- } // now xx is from 0 to 2.71...
- if (xx>2) // power series really bad for 2 to 2.71 so
- {
- nn+=0.69314718; // this is log 2
- xx/=2; // now xx is max 1.359
- }
- double x = xx - 1; // set up for power series
- double result = 0;
- int n = 1;
- double pow = -1;
- double term;
- do {
- pow *= -x;
- term = pow / n;
- n++;
- result += term;
- } while (abs(term)>1e-6);
- return result+nn;
- }
- if (xx == 1) {
- return 0;
- }
- // use Maclaurin series log(1-x)
- double x = 1 - xx;
- double result = 0;
- int n = 1;
- double pow = 1;
- double term;
- do {
- pow *= x;
- term = pow / n;
- n++;
- result -= term;
- } while (n < 500);
- return result;
- }
- static double exp(double x)
- { // standard power series for e^x
- double pow=1;
- double n=1;
- double result=1;
- double div=1;
- do
- {
- pow*=x;
- div*=n;
- result+=pow/div;
- n++;
- } while (n<50);
- return result;
- }
- static double pow(double x, double y)
- {
- return exp(y*log(x));
- }
- public static void main(String[] d) {
- // test log
- // System.out.println(log(-2)); //exception
- System.out.println(log(2.1)); //0.7419373466666667
- System.out.println(log(3)); //1.0986122718454672
- System.out.println(log(1)); //0.0
- System.out.println(log(0.5)); //-0.6931471805599451
- System.out.println(log(0.1)); //-2.302585092994046
- // test exp
- System.out.println(exp(2)); //7.389056098930649
- System.out.println(exp(5)); //148.41315910257657
- System.out.println(exp(1)); //2.7182818284590455
- System.out.println(exp(0.5)); //1.6487212707001278
- System.out.println(exp(0)); // 1.0
- System.out.println(exp(-1)); //0.36787944117144245
- // test pow
- System.out.println(pow(2,2)); //3.9999960000044585
- System.out.println(pow(2,3)); //7.999988000016374
- System.out.println(pow(4,-1)); //0.24999993536993692
- System.out.println(pow(3,2.1)); //10.04510821143608
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment