简体   繁体   中英

Rounding differences with Python, C, and JavaScript

I'm trying to multiply numbers and different languages are producing different results. Here is the math problem:

x = 3.0524116
y = 57325
z = x * y

With Python (and also JavaScript), z is 174979.49123897057 . Demonstration code is shown below.

import numpy as np
x = np.float32(3.0524116)
y = np.uint32(57325)
z = x * y
print(z)

With C, z is 174979.500000 . Demonstration code is shown below.

#include <stdio.h>
int main()
{
    float x = 3.0524116f;
    unsigned int y = 57325;
    float z = x * y;
    printf("%f\n", z);
    return 0; 
}

Now, when z is rounded to an integer in C, buffers that had been initialized in Python overflow and the whole thing goes over the cliff... Anyway, what is going on here? Why aren't the results the same?

I can reproduce your results if I use float in C, rather than double . Python's float type and JavaScript's Number are actually implemented with C double s, so if you want C to behave the same, use double , not float .

You're using the wrong type.

As others have pointed out, Python and JavaScript both used double s as opposed to float s. So for an accurate comparison with Python and Javascript, I tried this program:

#include <stdio.h>

int main()
{
    double x = 3.0524115349144454, y = 57325;
    printf("%.12lf\n", x * y);
    return 0;
}

When I run this, the output is 174979.491238970571 . That's exactly the same as 174979.49123897057 (except with 1 extra digit in C). So as you can see, it is the same, you were just using the wrong type (most probably, it would be good if you could clarify this in an edit).

I also ran the equivalent programs in Python and Javascript just to make sure, and the output was the same. I also ran the same C program except I replaced the double with float , and I got the output of 174979.500000000000 . So again, this is making me think you used float , though it would be good if you could clarify.

EDIT: I just noticed the edit you've made. However, the C tests and the Python tests are still not equivalent. In your python example:

import numpy as np
x = np.float32(3.0524116)
y = np.uint32(57325)
z = x * y
print(z)

x * y still returns a double-precision result which is then stored in a double precision float z . For an accurate test, you would have to replace z = x * y with z = np.float32(x * y) . When I try the Python program with the required change, I get 174979.5 , the same result as with C using float s. As for Javascript, I don't know how you've tested that or how you could use single-precision float s in it. I hardly know anything about the language, so I can't say really.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM