Solved

Calculate Pow() and Log() without using java.math

Posted on 2007-11-19
10
2,194 Views
Last Modified: 2010-05-18
Hi there,
I needed to do some mathematics in an exercice but I am not allowed to use the java.math class, I need to calculate the power Pow() and logarithm log()  with a custom base, base 10 would work as well.
thank you so much!
0
Comment
Question by:zorfael
  • 5
  • 3
  • 2
10 Comments
 
LVL 17

Expert Comment

by:CSecurity
ID: 20311776
You can use this POW function:

Example 8
 

double pow(double a, double b)

{

    // true if base is greater than 1

    boolean gt1 = (Math.sqrt((a-1)*(a-1)) <= 1)? false:true;

         

    int oc = -1; // used to alternate math symbol (+,-)

    int iter = 20; // number of iterations

    double p, x, x2, sumX, sumY;

        

    // is exponent a whole number?

    if( (b-Math.floor(b)) == 0 )

    {

        // return base^exponent

        p = a;

        for( int i = 1; i < b; i++ )p *= a;

        return p;

    }

        

    x = (gt1)?

            (a /(a-1)): // base is greater than 1

            (a-1); // base is 1 or less

                

    sumX = (gt1)?

            (1/x): // base is greater than 1

            x; // base is 1 or less

        

    for( int i = 2; i < iter; i++ )

    {

        // find x^iteration

        p = x;

        for( int j = 1; j < i; j++)p *= x;

            

        double xTemp = (gt1)?

                (1/(i*p)): // base is greater than 1

                (p/i); // base is 1 or less

            

        sumX = (gt1)?

                (sumX+xTemp): // base is greater than 1

                (sumX+(xTemp*oc)); // base is 1 or less

                    

        oc *= -1; // change math symbol (+,-)

    }

        

    x2 = b * sumX;

        

    sumY = 1+x2; // our estimate

                

    for( int i = 2; i <= iter; i++ )

    {

        // find x2^iteration

        p = x2;

        for( int j = 1; j < i; j++)p *= x2;

            

        // multiply iterations (ex: 3 iterations = 3*2*1)

        int yTemp = 2;

        for( int j = i; j > 2; j-- )yTemp *= j;

            

        // add to estimate (ex: 3rd iteration => (x2^3)/(3*2*1) )

        sumY += p/yTemp;

    }

        

    return sumY; // return our estimate

}

Open in new window

0
 
LVL 17

Accepted Solution

by:
CSecurity earned 200 total points
ID: 20311777
And easier one:

 public static int pow(int arg, int times){

int ret = 1;

for ( int i = 1 ; i <= times ; i++ ) {

ret = ret * arg;

}

return ret;

}

Open in new window

0
 
LVL 9

Assisted Solution

by:brunoguimaraes
brunoguimaraes earned 300 total points
ID: 20311791
public long pow(int x, int y) {

        long r = 1;

        for (int i = 0; i < y; i++) {
            r = r * x;
        }
        return r;
    }

   // base 2 log
    public int log(int x) {

        int r = 0;
        while ((x >> r) != 0) {
            r++;
        }
        return r - 1;
    }
0
 
LVL 2

Author Comment

by:zorfael
ID: 20317154
Thank you for your effort however the "Math" class can never be mentioned and Pow() should work with numbers like 0.53232333 for example and I can't pass a number like that as "int". the Log() function should be base 10 or custom base. In fact I need Pow() to calculate Exponential, Sin, Cosine, if you guys had those functions as well that would be great but with just the Pow() my numbers will come out good because they do if I use math.pow().
any other solutions?
thank you so much
0
 
LVL 2

Author Comment

by:zorfael
ID: 20317276
actually I made it to work with double numbers using brunoguimaraes solution but I still need a logarithm function that would the same value as the function below but whithout using the Math class:

public double Log(double a, double base)
{
   double x;
   x = math.log10(a)/math.log(base)
}

any ideas?
return x;
}
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 2

Author Comment

by:zorfael
ID: 20317280
CSecurity Pow() solution works just like brunoguimaraes's solution when updated to use double instead of int.
0
 
LVL 17

Expert Comment

by:CSecurity
ID: 20318356
My first example was in Double base itself:

double pow(double a, double b)
0
 
LVL 2

Author Comment

by:zorfael
ID: 20318863
sure, however you referenced "Math" on your code:
"Math.sqrt"
I can't use that but that's not the problem right now as I got that figured out,
I need to calculate the Logarithm in a custom base now, any ideas?
thank you!
0
 
LVL 9

Assisted Solution

by:brunoguimaraes
brunoguimaraes earned 300 total points
ID: 20319086
Try the code below. The greater the decimalplace parameter is, the greater the precision.
public static double log(double x, int base, int decimalplace) {

        

        int integer_value = 0;

        

        while (x < 1) {

            integer_value--; 

            x = x * base;

        }

        

        while (x >= base) {

            integer_value++;

            x = x / base;

        }

        double decimal_fraction = 0.0;

        double partial = 1.0;

        

        x = pow(x, 10);

        

        while (decimalplace > 0) {

            

            partial = partial / 10;

            int digit = 0;

            

            while (x >= base) {

                  digit++;

                  x = x / base;

            }

            decimal_fraction = decimal_fraction + digit * partial;
 

            x = pow(x, 10);

            decimalplace--;

        }

        return integer_value + decimal_fraction;

    }

Open in new window

0
 
LVL 2

Author Closing Comment

by:zorfael
ID: 31409916
thank you all!
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
groupSum5 challenge 5 71
Arduino EDI - Programming Language - Voice Recorder 4 70
session migration servlets 2 26
Apps blocked by Java 9 64
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
This article provides a brief introduction to tissue engineering, the process by which organs can be grown artificially. It covers the problems with organ transplants, the tissue engineering process, and the current successes and problems of the tec…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

896 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now