97

Here is my code. For some reason my BMI is not calculated correctly. When I check the output on a calculator for this : (10/((10/100)^2))) I get 1000, but in my program, I get 5. I'm not sure what I am doing wrong. Here is my code:

import javax.swing.*;

public class BMI {
    public static void main(String args[]) {
        int height;
        int weight;
        String getweight;
        getweight = JOptionPane.showInputDialog(null, "Please enter your weight in Kilograms");
        String getheight;
        getheight = JOptionPane.showInputDialog(null, "Please enter your height in Centimeters");
        weight = Integer.parseInt(getweight);
        height = Integer.parseInt(getheight);
        double bmi;
        bmi = (weight/((height/100)^2));
        JOptionPane.showMessageDialog(null, "Your BMI is: " + bmi);
    }
}
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
stytown
  • 1,642
  • 2
  • 16
  • 22

10 Answers10

159

^ in java does not mean to raise to a power. It means XOR.

You can use java's Math.pow()


And you might want to consider using double instead of int—that is:

double height;
double weight;

Note that 199/100 evaluates to 1.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
WuHoUnited
  • 8,279
  • 3
  • 24
  • 27
  • 3
    I see, I knew it had to be something very simple that I was doing wrong. Thank you. –  Jan 12 '12 at 21:23
  • In this case, it is probably OK, because accuracy doesn't matter for the seriously flawed BMI algorithm, sadly still used. When you do need decimal accuracy, better to use BigDecimal, because it doesn't suffer from inherent binary to decimal conversion errors of binary floating point numbers, because it uses decimal rather than binary scaling. – Infernoz Dec 17 '19 at 11:04
42

we can use

Math.pow(2, 4);

this mean 2 to the power 4 (2^4)

answer = 16

Thamays
  • 2,978
  • 26
  • 31
12

^ is not the operator you want. You are looking for the pow method of java.lang.Math.

You can use Math.pow(value, power).

Example:

Math.pow(23, 5); // 23 to the fifth power
Kevin Hooke
  • 2,583
  • 2
  • 19
  • 33
lhk
  • 27,458
  • 30
  • 122
  • 201
9

Your calculation is likely the culprit. Try using:

bmi = weight / Math.pow(height / 100.0, 2.0);

Because both height and 100 are integers, you were likely getting the wrong answer when dividing. However, 100.0 is a double. I suggest you make weight a double as well. Also, the ^ operator is not for powers. Use the Math.pow() method instead.

Bernard
  • 7,908
  • 2
  • 36
  • 33
  • 1
    Thank you. So now instead of giving me 1000, it gives me 999.9999 when I enter 10 and 10 as weight and height. It seems to be working much better now though. bmi = weight / Math.pow(height/100.00,2.00); – stytown Jan 12 '12 at 21:31
  • 1
    That depends on the precision of your `double` values. You can always round as the final step in the calculation if necessary. – Bernard Jan 12 '12 at 21:41
4

Too late for the OP of course, but still... Rearranging the expression as:

int bmi = (10000 * weight) / (height * height)

Eliminates all the floating point, and converts a division by a constant to a multiplication, which should execute faster. Integer precision is probably adequate for this application, but if it is not then:

double bmi = (10000.0 * weight) / (height * height)

would still be an improvement.

Chris Barry
  • 2,250
  • 1
  • 14
  • 8
3

You should use below method-

Math.pow(double a, double b)

From (https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#pow-double-double-)

Returns the value of the first argument raised to the power of the second argument.

Mr R
  • 754
  • 7
  • 19
PulkitRajput
  • 609
  • 6
  • 8
2

1) We usually do not use int data types to height, weight, distance, temperature etc.(variables which can have decimal points) Therefore height, weight should be double or float. but double is more accurate than float when you have more decimal points

2) And instead of ^, you can change that calculation as below using Math.pow()

bmi = (weight/(Math.pow(height/100, 2)));

3) Math.pow() method has below definition

Math.pow(double var_1, double var_2);

Example:

i) Math.pow(8, 2) is produced 64 (8 to the power 2)

ii) Math.pow(8.2, 2.1) is produced 82.986813689753 (8.2 to the power 2.1)

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
Kavindu Tharaka
  • 231
  • 2
  • 7
2
int weight=10;
int height=10;
double bmi;
bmi = weight / Math.pow(height / 100.0, 2.0);
System.out.println("bmi"+(bmi));
double result = bmi * 100;
result = Math.round(result);
result = result / 100;
System.out.println("result"+result);
preeti
  • 51
  • 1
  • 8
1

I did the benchmarking with Math.pow(x,2) and x*x, the result is that Math.pow() is easily forty times slower than manually multiplying it by itself, so i don't recommend it for anything where a little bit of performance is required.

Here's the results:

proof_of_work: 19.284756867003345
time for Math.pow(x,2) in ns: 35143
proof_of_work: 19.284756867003345
time for x*x in ns: 884
manual calculation is 39 times faster

and here's the test-code

double r1 = 4.391441320;
long multiply_d1 = System.nanoTime();
double multiply_dr = Math.pow(r1,2);
long multiply_d2 = System.nanoTime();
System.out.println(("proof_of_work: ") + (multiply_dr));
System.out.println(("time for Math.pow(x,2) in ns: ") + (multiply_d2 - multiply_d1));
long multiply_t1 = System.nanoTime();
double multiply_tr = r1*r1;
long multiply_t2 = System.nanoTime();
System.out.println(("proof_of_work: ") + (multiply_tr));
System.out.println(("time for x*x in ns: ") + (multiply_t2 - multiply_t1));
System.out.println(("manual calculation is ") + ((multiply_d2 - multiply_d1) / (multiply_t2 - multiply_t1)) + (" times faster"));
0

Most efficient solution is

public Float fastPow(Float number, Integer power) {
        if (power == 0) {
            return 1.0f;
        } else if (power % 2 == 1) {
            return fastPow(number, power - 1) * number;
        } else {
            return fastPow(number * number, power / 2);
        }
    }

Let A is our number and N our power. Then A^2^N = (A^2)^N. And A^N = (A^2)^N/2. The function above reflects this relationship.

rost
  • 3,767
  • 2
  • 10
  • 25