0

now i have a segment of code running online:

def div1(val, min, max, period):
    der = (max - min) / period # 0.005
    return val // der  # 41

# call div1
div1(0.21, 0, 1, 200)

when i call the function with div1(0.21, 0, 1, 200), i get the result of 41.

Now, i want to transform it to C++ language.

But in C++, i get 42 instead of 41.

int Box(double val, double min, double max, double period) {
    double der = (max - min) / period; // 0.005
    int final_val = floor(val / der); // 42
    return final_val;
}

Box(val, 0, 1, 200) // get 42

any thing wrong with my code? and how to fix it if i want to get the same result in C++?

ps: the code of Python CAN NOT be modified...

user3840170
  • 26,597
  • 4
  • 30
  • 62
  • 2
    But isn't `0.21/0.005=42`? I am quite lost here as to what the actual problem is. If you want to mimic python's weird behavior then you could just check if `double final_val` is an integer and subtract one before casting it and returning. Similar to: https://stackoverflow.com/questions/9898512/how-to-test-if-a-double-is-an-integer – Lala5th Apr 22 '22 at 06:19
  • 1
    The **wrong** output 41 is caused by rounding errors in the way `//` works - but note that this operator is meant to be used with integers, not with floats. Have a look at https://stackoverflow.com/questions/38588815/rounding-errors-in-python-floor-division for more details about this problem. – Thierry Lathuille Apr 22 '22 at 06:25
  • 1
    its unclear why `//` rounds `42.0` down to `41`, or why you want that. – 463035818_is_not_an_ai Apr 22 '22 at 06:28
  • @463035818_is_not_a_number maybe it's bug online, but can not be fixed yet, at leat in a short time. – hotdog5225 Apr 22 '22 at 06:59
  • @ThierryLathuille now i realize it's a bug online, but can not be fixed yet, since i have no right of the repo. – hotdog5225 Apr 22 '22 at 07:03
  • @Lala5th it's not working, i use `final_val == floor(final_val)` which tell me it's an int.... – hotdog5225 Apr 22 '22 at 07:05
  • Your current Python code is totally unreliable, as its result depends on the binary representation of floats. With slightly different arguments, your function would output a value larger by one than what you expect. The sane thing to do would be to use normal, float division, round (and not floor!) the result and subtract 1. – Thierry Lathuille Apr 22 '22 at 07:21

0 Answers0