Recursive Exponent Failing

2

I was practicing to be able to make a recursive exponent, and it works but not with doubles and floats , I do debugging and I get warnings in the implementation of C ++. It's a very long follow-up but in the end I get the next output. -1.#IND and if I put the return ternario comes out:

error LNK2019: unresolved external symbol "double __cdecl expo<double>(double,double)" (??$expo@N@@YANNN@Z) referenced in function _main
error LNK2019: unresolved external symbol "float __cdecl expo<float>(float,float)" (??$expo@M@@YAMMM@Z) referenced in function _main


This is my code:

#include <iostream>
template <typename TIPO>
TIPO expo (TIPO base, TIPO veces, TIPO cont = 1)
{
    cont *= base;
    if (veces < 0) return cont;
    expo(base, 1 - veces, cont);
    //lo mismo como operador ternario
    //return (veces > 0) ? expo(base, --veces, cont * base) : cont;
}
int main()
{
    float r = expo<float>(4.0,2.0);
    std::cout << r << std::endl;
    return 0;
}

Could someone tell me what my code is failing? Thanks for your time.

    
asked by Egon Stetmann. 17.09.2017 в 05:07
source

2 answers

2

Your role is curious ; with a notice:

  

warning: control reaches end of non-void function

Indicating that you do not return anything. And what do you do:

1 - veces

will not it be the other way around?

template< typename T > T expo( T base, T ex, T acu = 1 ) {
  return ex > 0 ? expo( base, ex - 1, acu * base ) : acu;
}

And, for the float numbers, the f indicator is used. Otherwise, take them as double .

float r = expo( 4.0f, 2.0f );

And one last point: working with floating-point numbers, the result is imprecise ; a recursive function that accumulates inaccuracies ... because the result is not very similar to what you expect: -)

    
answered by 17.09.2017 / 07:17
source
2

The first weird thing about your function is that you are using decimal exponents and you have not foreseen anything to calculate the result in case the number has decimals. So the exponent should be whole.

On the other hand, you should take into account that x^0=1 and it would already be at your discretion whether or not to treat the negative exponents ... in this case we will assume that they are not valid:

template<typename Type>
Type expo(Type base, unsigned int exponente)
{
  if( exponente == 0 )
    return 1;
  else
    return base * expo(base,exponente-1);
}

When using this function with float or double you can suffer precision penalties and this is because float has (typically) 6 representative digits (the rest are garbage) and double about 12.

    
answered by 17.09.2017 в 17:10