# Does mod() work? Or am I high?

**URL:** https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093
**Category:** General Usage
**Created:** [September 17, 2018, 8:33pm UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093 "2018-09-17T20:33:11Z")
**Posts on this page:** 20
**Page:** 1

<div class="post-metadata">

### Author: ![GlenHenshaw](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/glenhenshaw/32/5269_2.png) [@GlenHenshaw](https://discourse.julialang.org/u/GlenHenshaw)
#### Post date: [September 17, 2018, 8:33pm UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/1 "2018-09-17T20:33:11Z")

</div>

```
julia> mod(1.0, 0.1)
0.09999999999999995

```

Shouldn’t this be exactly zero, or at least pretty close to zero?

```
julia> mod(1.1, 0.1)
2.7755575615628914e-17

```

Like this, for instance?

---

<div class="post-metadata">

### Author: ![simonbyrne](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/simonbyrne/32/19_2.png) [@simonbyrne](https://discourse.julialang.org/u/simonbyrne)
#### Post date: [September 17, 2018, 8:41pm UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/2 "2018-09-17T20:41:21Z")

</div>

The literal `0.1` isn’t 0.1, but the closest `Float64` to it:

```julia
julia> using Printf

julia> @printf "%.60f" 0.1
0.100000000000000005551115123125782702118158340454101562500000

```

It is larger than 0.1, so

```julia
julia> fld(1.0,0.1)
9.0

julia> fma(-9.0, 0.1, 1.0) # 1.0 - 9.0 * 0.1 without rounding
0.09999999999999995

```

---

<div class="post-metadata">

### Author: ![GlenHenshaw](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/glenhenshaw/32/5269_2.png) [@GlenHenshaw](https://discourse.julialang.org/u/GlenHenshaw)
#### Post date: [September 17, 2018, 8:43pm UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/3 "2018-09-17T20:43:28Z")

</div>

and yet, in Matlab:

```
>> mod(1.0, 0.1)

ans =

     0

```

---

<div class="post-metadata">

### Author: ![StefanKarpinski](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stefankarpinski/32/24_2.png) [@StefanKarpinski](https://discourse.julialang.org/u/StefanKarpinski)
#### Post date: [September 17, 2018, 8:49pm UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/4 "2018-09-17T20:49:36Z")

</div>

Matlab is lying to you.

[https://g.co/kgs/BcUoEy](https://g.co/kgs/BcUoEy)

---

<div class="post-metadata">

### Author: ![bkamins](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bkamins/32/208538_2.png) [@bkamins](https://discourse.julialang.org/u/bkamins)
#### Post date: [September 17, 2018, 9:02pm UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/5 "2018-09-17T21:02:45Z")

</div>

However, something like this might surprise a Julia user:

```julia
julia> test(x,y) = x - y*round(x/y, RoundToZero) - rem(x,y)
test (generic function with 1 method)

julia> test(1.0, 0.1)
-0.09999999999999995

```

reading the documentation (even if it states _without any intermediate rounding_, which is not an obvious disclamer).

EDIT:  
I am aware of:

```julia
julia> round(big(1.0)/big(0.1), RoundToZero)
9.0

```

and

```julia
julia> Float64(rem(Rational{BigInt}(1.0), Rational{BigInt}(0.1)))
0.09999999999999995

```

But this does not change that I think users might be confused, so maybe we should explain it better.

---

<div class="post-metadata">

### Author: ![JeffreySarnoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreysarnoff/32/1980_2.png) [@JeffreySarnoff](https://discourse.julialang.org/u/JeffreySarnoff)
#### Post date: [September 17, 2018, 9:10pm UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/6 "2018-09-17T21:10:34Z")

</div>

These are the tests to consider:

```julia
julia> test2(x,y) = x - fma(y, div(x, y), rem(x,y))
julia> test2(1.0,0.1)
0.0

julia> test3(x,y) = x - fma(y, fld(x, y), mod(x,y))
julia> test3(1.0,0.1)
0.0

```

---

<div class="post-metadata">

### Author: ![bkamins](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bkamins/32/208538_2.png) [@bkamins](https://discourse.julialang.org/u/bkamins)
#### Post date: [September 17, 2018, 9:13pm UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/7 "2018-09-17T21:13:43Z")

</div>

> [@JeffreySarnoff](#):
>
> These are the tests to consider:

I agree, but currently the documentation of `rem` uses `round` (that is why I have written that maybe we should improve it).

---

<div class="post-metadata">

### Author: ![GlenHenshaw](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/glenhenshaw/32/5269_2.png) [@GlenHenshaw](https://discourse.julialang.org/u/GlenHenshaw)
#### Post date: [September 17, 2018, 10:06pm UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/8 "2018-09-17T22:06:36Z")

</div>

> [@JeffreySarnoff](#):
>
> x - fma(y, fld(x, y), mod(x,y))

Neither of these tests does what I expect:

```
julia> x = 1.0
julia> y = 0.3
julia> x - fma(y, fld(x, y), mod(x,y))
0.0

```

To be clear, I’m looking for a function that returns zero when the value x is evenly divisible by y, and non-zero otherwise. Or, following the above point, when x is _very close_ to being evenly divisible by y.

It appears that perhaps what I want is captured by:

```
x - trunc(x/y)*y

```

---

<div class="post-metadata">

### Author: ![bkamins](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bkamins/32/208538_2.png) [@bkamins](https://discourse.julialang.org/u/bkamins)
#### Post date: [September 17, 2018, 10:29pm UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/9 "2018-09-17T22:29:32Z")

</div>

> [@GlenHenshaw](#):
>
> x - trunc(x/y)\*y

You will still have a problem if you take e.g. `x = prevfloat(1.0)` or `y = nextfloat(0.1)`.

If you really want something that is _very close to zero_ then maybe something like this will do what you want:

```julia
f(x,y) = min(abs(mod(x,y)), abs(mod(x,-y)))

```

which gives you a minimum deviation to being closely divisible from below and above.

---

<div class="post-metadata">

### Author: ![stillyslalom](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stillyslalom/32/45687_2.png) [@stillyslalom](https://discourse.julialang.org/u/stillyslalom)
#### Post date: [September 17, 2018, 10:33pm UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/10 "2018-09-17T22:33:15Z")

</div>

It isn’t quite lying, it’s just being Matlab. From their [docs](https://www.mathworks.com/help/matlab/ref/mod.html),

> Note that `mod` attempts to compensate for floating-point round-off effects to produce exact integer results when possible.

---

<div class="post-metadata">

### Author: ![JeffreySarnoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreysarnoff/32/1980_2.png) [@JeffreySarnoff](https://discourse.julialang.org/u/JeffreySarnoff)
#### Post date: [September 17, 2018, 11:02pm UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/11 "2018-09-17T23:02:57Z")

</div>

this is substantively faster, if it works for you: `g(x,y) = mod(-abs(x), abs(y))`  
However, it is incorrect for e.g. g(1.0,1/3)

---

<div class="post-metadata">

### Author: ![jandehaan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jandehaan/32/6805_2.png) [@jandehaan](https://discourse.julialang.org/u/jandehaan)
#### Post date: [September 17, 2018, 11:41pm UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/12 "2018-09-17T23:41:36Z")

</div>

Also consider `h(x,y) = (z=x/y; z-trunc(z) == 0.0 ? 0.0 : mod(x,y))`  
`h(1.0, 0.1)` yields `0.0` and `h(1.0, 1/3)` yields `0.0` too.  
It seems to work, but do your own tests to verify.

---

<div class="post-metadata">

### Author: ![simonbyrne](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/simonbyrne/32/19_2.png) [@simonbyrne](https://discourse.julialang.org/u/simonbyrne)
#### Post date: [September 17, 2018, 11:55pm UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/13 "2018-09-17T23:55:02Z")

</div>

> [@GlenHenshaw](#):
>
> To be clear, I’m looking for a function that returns zero when the value x is evenly divisible by y, and non-zero otherwise. Or, following the above point, when x is _very close_ to being evenly divisible by y.

Well, that depends how you define “evenly divisible” in the context of floating point. Perhaps if you explained the context in which you want it?

---

<div class="post-metadata">

### Author: ![bkamins](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bkamins/32/208538_2.png) [@bkamins](https://discourse.julialang.org/u/bkamins)
#### Post date: [September 18, 2018, 1:50am UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/14 "2018-09-18T01:50:51Z")

</div>

> [@JeffreySarnoff](#):
>
> g(x,y) = mod(-abs(x), abs(y))

The problem with this definition is:

```julia
julia> g(1.0, 1/3)
0.33333333333333326

```

if I understand the original question correctly.

---

<div class="post-metadata">

### Author: ![GlenHenshaw](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/glenhenshaw/32/5269_2.png) [@GlenHenshaw](https://discourse.julialang.org/u/GlenHenshaw)
#### Post date: [September 18, 2018, 1:59am UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/15 "2018-09-18T01:59:40Z")

</div>

My specific problem is that I have implemented a model predictive control algorithm. This can be thought of as an algorithm that runs at a fast, hopefully-but-not-really-constant rate and calculates some output that gets sent to a hardware device. I want to output the output of the routine at some slower rate, but at a hopefully-nearly-constant time interval. As an example, my routine runs at approximately 100 iterations per second, and I want output at 10 iterations per second. Note that the output rate can vary at the user’s discretion, but should always be approximately an even divisor of the inner loop running rate.

Internally, elapsed time is available to me. The tempting thing to do, therefore, is to call time “t” and desired output rate “dt”, and call a routine to record the output whenever mod(t, dt) is approximately zero.

Also note that although I am using Julia, this is because I am the algorithm prototyper. The eventual target code will be implemented in C, by a hard-realtime software engineer who frowns on garbage collection, dynamic memory allocation, and really any advanced language features. So I am somewhat limited in the language features I can use. Iterators, for instance, are probably not viable here.

The other obvious way to do this, of course, would be to set up a counter and output when the counter reaches zero. This has the disadvantage that if my running rate ever varies (eg it slows down), my output rate will vary also. Which is not acceptable in my application.

---

<div class="post-metadata">

### Author: ![JeffreySarnoff](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jeffreysarnoff/32/1980_2.png) [@JeffreySarnoff](https://discourse.julialang.org/u/JeffreySarnoff)
#### Post date: [September 18, 2018, 2:01am UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/16 "2018-09-18T02:01:51Z")

</div>

well – if you want to get technical 🙂  
here is one, about 2x the original with the advantage of giving 0.0 rather than close to zero for a number of inputs

```julia
function h(x,y)
    a = x*inv(y)
    a - trunc(a)
end

```

---

<div class="post-metadata">

### Author: ![johnh](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/johnh/32/3615_2.png) [@johnh](https://discourse.julialang.org/u/johnh)
#### Post date: [September 18, 2018, 11:41am UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/17 "2018-09-18T11:41:54Z")

</div>

@GlenHenshaw please watch the Julia Robotics talk at JuliaCom2018  
They have the very same requirements you have - and a control loop which needs to run at 1000Hz  
they had to avoid allocations in the inner tight loop.  
Please listen to the questions at the end - where Valentin is asked about a macro which will avoid allocations.  
And it is promised! 38:40 into the presentation, during questions

[![](https://global.discourse-cdn.com/julialang/original/3X/0/b/0b71256d516593ad3b81147b0fb018d0cc526872.jpeg "JuliaRobotics: Making robots walk with Julia | Robin Deits") ](https://www.youtube.com/watch?v=dmWQtI3DFFo)

---

<div class="post-metadata">

### Author: ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)
#### Post date: [September 18, 2018, 3:31pm UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/18 "2018-09-18T15:31:31Z")

</div>

> [@GlenHenshaw](#):
>
> The tempting thing to do, therefore, is to call time “t” and desired output rate “dt”, and call a routine to record the output whenever mod(t, dt) is approximately zero.

That seems dicey to me. If by “approximately zero” you mean `abs(mod(t, dt)) < ε` for some `ε`, then if you make `ε` too small you risk outputting very infrequently (because your code only gets called at a _discrete_ set of times `t`, which may not often be close to multiples of `dt`), and if you make `ε` too large then you risk outputting multiple times in the same `dt` time interval.

Why not do something like:

```julia
t = time()
if t >= last_output_time + dt
    ...output...
    last_output_time = t
end

```

That way it will call the output routine as close as possible to intervals of `dt`, limited by the frequency of the times `t` where you perform this check.

---

<div class="post-metadata">

### Author: ![y4lu](https://avatars.discourse-cdn.com/v4/letter/y/47e85d/32.png) [@y4lu](https://discourse.julialang.org/u/y4lu)
#### Post date: [September 19, 2018, 2:05am UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/19 "2018-09-19T02:05:23Z")

</div>

It might be possible to use the Rational type

```julia
julia> 1 % 1//10 == 0
true
```

---

<div class="post-metadata">

### Author: ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)
#### Post date: [September 19, 2018, 7:46am UTC](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093/20 "2018-09-19T07:46:53Z")

</div>

Very good point. Operations like these are actually one of the most important use cases of `Rational`. It is not in the `Base` by accident, or purely as a demo for parametric constructors 😉

[Next page](https://discourse.julialang.org/t/does-mod-work-or-am-i-high/15093.md?page=2)
