Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Math.pow(long, (1/3)) always returns 1?

Tags:

java

math

If problem is in power, how to write it correctly?

like image 865
Ilya Avatar asked Feb 21 '11 12:02

Ilya


2 Answers

This is because 1/3 is integer division, and it evaluates to 0. You are effectively raising to the 0th power, which always yields 1. Try 1.0/3.0 instead.

like image 192
Sven Marnach Avatar answered Oct 12 '22 19:10

Sven Marnach


Try Math.pow(long, 1D/3).

By default, numeric literals in Java are considered as ints. So, 1/3 is converted to 0 and not 0.33333 as should be the case. Qualifying it with 1D or 1F or 1.0 will solve the problem.

like image 45
adarshr Avatar answered Oct 12 '22 18:10

adarshr