0

Hey there. I'm trying to raise a longs to the second power, but as you might know, Math.pow takes two doubles, and also returns a double.

Efficiency is kind of important, but it is more important to have this working.

Do you know how I might go about solving this?

Thanks for all input!

6
Contributors
9
Replies
10
Views
5 Years
Discussion Span
Last Post by NormR1
1

so why not write your own pow class that accepts two floats and returns a float?

public float pow(float f1, float f2) {
        float answer = 0;
        //calculate f1 to the power of f2 and store in answer
        return answer;
    }
0

Thank you. Can't belive I didnt think of that. I was too busy looking for packages with this function...
Does this look good?

public float pow(float first, float second){
        for(int i = 1; i < second; i++){
            first *= first;
        }
        return first;
    }

EDIT: How do you make the code look better, like in your example?

Edited by joankim

1

You should start your for loop counter at 0. Not only because your for loop doesnt quite work as it is now, it raises to a power one less than what the user asks for. But also because its good coding practice!

1

Have you tested the code? If you change the value of first what happens to the computation?

second is a poor name for the variable with the power value

0

Krocky, it does work as it should. And I prefer starting i at one because it's more practical and efficient than

for(int i = 0; i < second-1;i++){

And yeah, the code works as it is supposed to. And I agree second is a bad name, I was kind of in a rush. But do you think it would be better not to change the value of first, like this?

     public float pow(float first, float power){
     float returnedValue = first;
     for(int i = 1; i < power; i++){
         returnedValue *= first;
     }
     return returnedValue;
 }

Edited by joankim

1

Why not name them public float pow(float base, float exponent)

public float pow(float first, float power){

`

1

I prefer starting i at one because it's more practical and efficient than

You will need to get used to starting indexes at 0. EVERYTHING works that way.

I don't think the earlier code gave the desired results.
This code looks better.

Edited by NormR1

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.