0

I need to take a root of a number, N being the number, x being the root.

2^(1/x)

^ being a power, not XOR.

I've tried using the POW function, but whenever I try to put a variable as the second argument, it hates me real bad.

#include <stdio.h>
#include <math.h>

int main(int argc, char **argv)
{
    double root = 4;
    double root_result = 0;

    root_result = pow(2,1/root);

    printf("%f",root_result);
    return 0;
}

Linker error:

untitled.c:(.text+0x34): undefined reference to `pow' 

There is probably a better option out there. The only other function I can find is exp, but those are base e functions, which is not really helpful in my case.

Would something like this work?

exp(log(abs(1))/n))

n being the root I would want.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user3287789
  • 121
  • 2
  • 11
  • possible duplicate of [C - undefined reference to sqrt](http://stackoverflow.com/questions/5248919/c-undefined-reference-to-sqrt) – Jonathan Leffler Feb 27 '14 at 23:50
  • 1
    The log/multiply/antilog approach may be subject to limitations of precision being amplified by the exp() operation... but it's certainly one way to get the value for powers not otherwise supported. – keshlam Feb 28 '14 at 00:00
  • 1
    I don't think the `abs()` is needed (`abs(1) == 1` - but you probably wanted 2 instead of 1 anyway), and using `exp()` and `log()` would provide more or less the correct answer, but you'd run into the equivalent linking problem -- the functions would be in the maths library. – Jonathan Leffler Feb 28 '14 at 00:00

1 Answers1

2

Add -lm to the linking command line to include the maths library. Some platforms require this; others do not. Given the error, the chances are strong that yours does require -lm.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • wow, that worked. Is there a way i can get around using that linker? – user3287789 Feb 27 '14 at 23:52
  • 2
    There isn't a way to avoid linking the maths library when you use functions from the maths library. Once upon a long time ago, not all machines included an FPU (floating-point unit), so you sometimes needed a maths library that included floating-point emulation and sometimes you needed the version that used the hardware FPU. So, the maths library was kept separate to allow switching more easily. As I noted, some platforms include the maths functions in the main standard library, and you then don't need the `-lm` linker option (but there's an empty library so if you use it, there's no error). – Jonathan Leffler Feb 27 '14 at 23:56