-4

I have the following equation I need to represent in C:

20 * 2^((1-x)/5)

my c representation is as follows, but it seems like the pow function is always returning a high integer value (1073741824) with my n values ranging from 1-5.

double x = 20 * pow(2.0, (n/5.0));

I assume it is because both arguments are not double values, but I do not see why. Is there a different way to format this equation to get it to work?

Clarko
  • 103
  • 5
  • 1
    Welcome to Stack Overflow. Please read the [**About**](http://stackoverflow.com/tour) page soon and also visit the links describing [**How to Ask a Question**](http://stackoverflow.com/questions/how-to-ask) and [**How to create a Minimal, Complete, and Verifiable example**](http://stackoverflow.com/help/mcve). What is `n` ? Suggest `((1.0 - n)/5.0)`. – David C. Rankin Feb 21 '20 at 07:49
  • When setting `n=2` I get `x=17.411011` which seems correct to me - what did you expect and what did you get? – Odysseus Feb 21 '20 at 08:00
  • I edited the question, I have included math.h. – Clarko Feb 21 '20 at 08:13

2 Answers2

3

I just compiled the example you give and it works

#include <stdio.h>
#include <math.h>
int main () {
    for (int n = 1; n <= 5; ++n) {
        double x = 20 * pow(2.0, ((1-n)/5.0));
        printf("%lf ", x);
    }
}

Output

20.000000 17.411011 15.157166 13.195079 11.486984

Make sure you use int n and not unsigned n. In case of unsigned you will get (1 - n) overflow and pow will return inf.

Tarek Dakhran
  • 2,021
  • 11
  • 21
  • 1
    problem must be somewhere else in the program, thank you for taking the time. I will ask another question if I can't figure it out for myself. – Clarko Feb 21 '20 at 07:58
2

Your compiler is assuming pow() returns an int,

Remeber to #include <math.h> for the proper prototype

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

// ipow works as pow when the compiler assumes an int return value
int ipow(double base, double exp) {
    double res = pow(base, exp);
    return *(int*)((void*)&res);
}

int main(void) {
    for (int n = 1; n < 6; n++) {
        double x = 20 * pow(2.0, ((1-n)/5.0));  // with correct prototype
        double y = 20 * ipow(2.0, ((1-n)/5.0)); // when compiler assumes int
        printf("n=%d, x=%f, y=%f\n", n, x, y);
    }
    return 0;
}

See https://ideone.com/XvPWX6

Output:

n=1, x=20.000000, y=0.000000
n=2, x=17.411011, y=422418048.000000
n=3, x=15.157166, y=1240833840.000000
n=4, x=13.195079, y=-1971682192.000000
n=5, x=11.486984, y=-2036727536.000000
pmg
  • 106,608
  • 13
  • 126
  • 198