HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Raising a number to an integral power

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
integralnumberpowerraising

Problem

I'm currently learning Java along with the Stanford online "Programming Methodology" course and, while it is awesome, I do lack any kind of human feedback.

This exercise was to create a method that took a floating-point value x and an integer k and returned x to the power of k. The method needed to also be able to correctly calculate the result when k is negative using the relationship \$x^{-k} = \frac{1}{x^k}\$.

/*
 * File: RealPower.java
 * ---------------------
 * This Method takes a floating-point value 'x'
 * and an integer value 'k' and returns 'x to the power
 * of k'. Method is written to correctly calculate
 * even when 'k' is negative.
 * Program displays a table of values generated using
 * the raiseRealToPower method. where x = PI 
 * and y is generated by 'i' variable in 'for' loop.
 * ---------------------
 * coded by Dartias
 */

import acm.program.*;

public class RealPower extends ConsoleProgram {

    public void run() {

        println("This program raises displays PI to the power of -4 through 4.");

/*
 * assigns 'x' the named constant value stored in PI        
 */

        double x = PI;

/*
 * this loop uses the raiseToRealPower method to generate the
 * values for powers of -4 through 0.
 */

        for(int i = -4; i =0){
        for(int i = 1; i < k; i++){
            total *= x;
        }} else {
            k = Math.abs(k);
            for(int i = 1; i < k; i++){
                total *= x;
            }
            total = (1/total);
        }
    return total;
    }

/*
 * defines the named constant PI and assigns it a value.
 */

private static final double PI = 3.14159265;

}

Solution

If you are a beginner, thats what you do and look at the results. It is good.

If this would be a real problem, there are substantially more efficient solutions: Your solution is linear in x: For each unit in x you make 1 multiplication. There is however a logarithmic solution possible: In each step, compute the square of the factor of the previous step. If this factor occurs in the original x, multiply the result with the factor.
I know this a shortish description, but you want to learn, right?

if it were real I wouldn't call max but look at the sign bit. If it were real I would also add overflow, or, underflow tests.

Lastly, I would stronger separate the computation from the output display. Comments are good, but you have overcommented. The purpose of the comment is to help understand the program, not obscure.

Context

StackExchange Code Review Q#64331, answer score: 7

Revisions (0)

No revisions yet.