Member Avatar for joankim

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!

Member Avatar for joankim

BUMP!

What's wrong with myLong * myLong ?

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;
    }
Member Avatar for joankim

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?

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!

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

Member Avatar for joankim

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;
 }

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

public float pow(float first, float power){

`

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.