Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Math.pow is not working [duplicate]

Tags:

java

pow

System.out.println(Math.pow(16, 0.5)); is 4.0

and

System.out.println(Math.pow(16, (1/2)));  is 1.0

Why??? I need to use fraction!

like image 484
Apetrei Ionut Avatar asked Jun 01 '26 21:06

Apetrei Ionut


1 Answers

1/2 is 0, due to integer division, so Math.pow(16, (1/2) is Math.pow(16, 0), which is 1.0.

In order for 1/2 to be evaluated using floating point division, you have to cast either 1 or 2 to double :

System.out.println(Math.pow(16, ((double)1/2)));

Or use double literal in the first place :

System.out.println(Math.pow(16, (1.0/2)));

or

System.out.println(Math.pow(16, (1/2.0)));
like image 135
Eran Avatar answered Jun 04 '26 10:06

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!