0

I am trying to build an exponentiation function for real numbers where I cannot use the Math library in Java. The only operators I am allowed to use are +, -, * and /. No sqrt or log or any other function other than these 4 operators. I am able to do it for a whole number since it is pretty easy but cannot figure out how to for real numbers... Both the base and exponent can be real numbers

public static void power(){

        System.out.println("\nPower function... ");
        System.out.println("Enter the base: ");
        long base = scan.nextLong();
        System.out.println("Enter the exponent: ");
        long exp = scan.nextLong();
        System.out.println("Calculating " + base + "^" + exp + "...");

        long answer = 1;
        while(exp != 0) {
            answer *= base;
            exp--;
        }
        System.out.println(answer); 
}
harcles
  • 1
  • 1
  • so your problem is if the exp is something like" 3,14"? – Alberto Sinigaglia Jun 03 '20 at 22:00
  • Do you need it to work only for real number bases or real number exponents as well? – Charlie Armstrong Jun 03 '20 at 22:01
  • 1
    What you have here is a maths question. Maybe you should ask it on a maths website. – khelwood Jun 03 '20 at 22:01
  • yes, any exponent that is a real number, and the base can also be a real number – harcles Jun 03 '20 at 22:01
  • 1
    if you are able to calculate the SQRT (use something like Newton method) you can rewrite the exp as a/b, and so calculate base^a and then calculate the b-th root of that number – Alberto Sinigaglia Jun 03 '20 at 22:08
  • 2
    If you don't know that the exponent is an integer, that makes it an extremely hard function to write. However, it sounds like you are basically trying to re-create Java's `Math.pow` method in your own code. This has already been posted [here](https://stackoverflow.com/questions/38236538/whats-the-algorithm-behind-math-pow-in-java) – Charlie Armstrong Jun 03 '20 at 22:08
  • 1
    You solution also does not work with negative exponentiation. – Quang Nguyen Jun 03 '20 at 22:09
  • see [Power by squaring for negative exponents](https://stackoverflow.com/a/30962495/2521214) and just pick a method. Either log/exp (which you must implement) or power by squaring for integer part * power by sqrting for fractional part of exponent. – Spektre Jun 04 '20 at 06:20

0 Answers0