Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate a^(1/n)?

I am trying to calculate a^(1/n), where ^ denotes exponentiation.

However, the following:

Math.pow(8, 1/3)

returns 1.0 instead of returning 2.0.

Why is that?

like image 608
GltknBtn Avatar asked Apr 11 '13 17:04

GltknBtn


People also ask

What is the sum of 1 to n?

The formula of the sum of first n natural numbers is S=n(n+1)2 .

How do you calculate the power of n?

If n is a positive integer and x is any real number, then xn corresponds to repeated multiplication xn=x×x×⋯×x⏟n times. We can call this “x raised to the power of n,” “x to the power of n,” or simply “x to the n.” Here, x is the base and n is the exponent or the power.


2 Answers

The problem is that 1/3 uses integer (truncating) division, the result of which is zero. Change your code to

Math.pow(8, 1./3);

(The . turns the 1. into a floating-point literal.)

like image 142
NPE Avatar answered Sep 21 '22 13:09

NPE


1/3 becomes 0(Because 1 and 3 are taken as int literals).

So you should make those literals float/double...

Do:

Math.pow(8, 1f/3) or

Math.pow(8, 1./3) or

Math.pow(8, 1.0/3)

like image 40
Sam Avatar answered Sep 17 '22 13:09

Sam