C ++ or c pow gives wrong result

im trying to make my own role but i get the wrong result

im getting: 2 ^ 3.3 = 16, which is wrong ... why?

#include <iostream> using namespace std; double new_pow(double base, double power){ double result = 1; for(int i = 0; i <= power; i++) { result *= base; } return result; } int main (int argc, char * const argv[]) { std::cout << new_pow(2,3.3) << endl; return 0; } 

Please help me find a mistake

+1
source share
5 answers

Ignacio's answer already mentions the use of logarithms. But in the end, we use exp() , which again is a library function. Therefore, if you do not want to use library functions at all, you need to resort to something like Taylor Extension x^y

Since a direct estimate of the Taylor expansion for x^y tedious, as Ignacio mentioned, base^power = exp( power*ln(base) ) . And the taylor extension for e ^ x is pretty simple and that for ln (x) is also very simple. Both of them give for a simple mutually recursive implementation in C

Here is a simple implementation of e^x using the above Taylor extension

 double pow_x ( double x , unsigned i ) { double prod=1; if ( i == 0 ) return 1; while ( i ) { prod*=x; i--; } return prod; } long long factorial ( unsigned n ) { if ( n == 0 ) return 1; return n * factorial (n-1); } double expo ( double x, int terms ) { /* terms tells us how long should we expand the taylor series */ double sum=0; unsigned i=0; while ( i< terms ) { sum+= pow_x(x,i)/factorial(i); i++; } return sum; } 

exp(5.93,20) gives 376.152869 , which Google generally agrees.

Hopefully using this example, you can implement ln(x) yourself.

+3
source

The error is that your loop runs 4 times, since it will not be more than 3.3 for 4 iterations. This is why floating point exponentiation is implemented with logarithms, not re-multiplication.

+5
source

Since you increase i by 1., after 4.0 it will automatically increase to 5.0 , thereby making the loop state check false and thereby ending the loop.

Also, your initial value for the loop variable is 0 , so you should check it like this:

 for(double i=0; i<power; i++) 

You can take a look at this answer to get an idea of ​​how to implement floating point elevation here too for a fairly high level of implementation.

0
source
 for(int i = 0; i <= power; i++) 

it should be

 for(int i = 1; i <= power; i++) 

Otherwise, it will work for one additional iteration.

As mentioned in Ignacio Vasquez-Abram. Suppose you need the force y = x ^ b. This is equivalent to ln (y) = b * ln (x).

so y = exp(b*ln(x))

 y = Math.e(b*Math.Log(x)) //Java 
0
source

You execute the loop, treating power as int . The cycle will be executed 4 times, and returns the 2^4 = 16 .

How to approximate decimal values ​​using logarithms .

0
source

Source: https://habr.com/ru/post/1496596/


All Articles