Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using modulus operator with floats

Somebody asked this question on a programming contest:-

-1%1000000009 is -1 or 1000000008

I want to know, is this even possible? I tried in my system, got -1 every time. Also, I had to find out 10^-9 % 10^9, I used fmod and got answer 1e-009, shouldn't it be 1?

My interpretation:- 10^-9/10^9 = 1/10^18 So, answer = 1.

Please tell me where I am wrong.

like image 728
unixia Avatar asked Oct 20 '22 07:10

unixia


1 Answers

preview : ( i will refer mod as %)

Just like in 1%3 , we do (int) 1/3 which is 0 , and then we ask : how many to add in order to get 1 ?

the answer is 1.

so 1%3=1.


Looking at 10^-9 % 10^9

let's use another numbers , for clarity :

2^-3 % 2^3

first we calc the integer value of the deviation:

2^-3 / 2^3 = 1/(2^3 * 2^3) = 1/64

as you can see it's a small number

so the int part is 0.

so - how many to add in order to get 2^-3 ? that's right : 2^-3


regarding your exact question :

My interpretation:- 10^-9/10^9 = 1/10^18 So, answer = 1.

1/10^18 indeed.

what's the integer part ? a zero.

from that zero , how much we need to add to get to -1 ?

yup , -1.

just follow the rules of Modulo .

first find the integer deviation. and then ask : how much we need to add in order to get to numerator .

edit:

for a situation where numerator >denominator

7 % 5 = > 7 /5 => 1.4 => .4 go to hell = > you're left with 1.

but notice.

this is 1 times 5.

ok so from 1 times 5 - how much it takes to go to 7 ? yes : 2.

more advanced :

3.111 %2 = > 3.111/2 = > 1.5555 => .555 go to hell => you're left with 1.

but that's 1 times of 2.

so from 1 times of 2 - how much it takes to go to 3.111 ? yup 1.111

like image 124
Royi Namir Avatar answered Oct 23 '22 03:10

Royi Namir