vehomzzz
vehomzzz

Reputation: 44568

std::pow gives a wrong approximation for fractional exponents

Here is what I mean trying to do

 double x=1.1402
 double pow=1/3;
 std::pow(x,pow) -1;

result is 0 but I expect 0.4465

the equation is (1 + x) ^3= 1.1402, find x.

Upvotes: 8

Views: 9332

Answers (4)

Jerry Coffin
Jerry Coffin

Reputation: 490098

1/3 is done as integer arithmetic, so you're assigning 0 to pow. Try pow(x, 1.0/3.0);

Upvotes: 13

Mark Ransom
Mark Ransom

Reputation: 308121

Many have stated that 1/3 = 0, but have not explained why this is so.

C and C++ will perform the operation based on the the types of the operands. Since both operands are integers, it performs an integer division creating an integer result. When it is forced to assign that integer result to a double variable, it converts the integer 0 to a double 0.0.

It is not necessary to make both operands double, if either one is double the compiler will convert the other to double as well before performing the operation. 1.0/3 or 1/3.0 will both return the result you expected, as will 1.0/3.0.

Upvotes: 9

Doug T.
Doug T.

Reputation: 65599

your 1/3 is integer division, the result of the integer division is 0.

Upvotes: 1

GManNickG
GManNickG

Reputation: 503805

1/3 is 0. That's integer division.

Try:

double pow = 1.0 / 3.0;

For:

#include <iostream>
#include <cmath>

int main(void)
{
 double x = 1.1402;
 double pow = 1.0/3.0;
 std::cout << std::pow(x, pow) - 1;

}

Upvotes: 23

Related Questions