Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

Mod() using floats


  • Please log in to reply
8 replies to this topic
JambaFun
  • Members
  • 7 posts
  • Last active: Nov 10 2007 07:30 PM
  • Joined: 17 May 2007
Hey,

Please explain this:

Mod(10,1) -> 0
Mod(1.0,0.1) -> 0.1

It seems like a bug to me...


Cheers!

SKAN
  • Administrators
  • 9115 posts
  • Last active:
  • Joined: 26 Dec 2005
:D

Use Round()

If Round( Mod(1.0,0.1) ) 
   MsgBox


JambaFun
  • Members
  • 7 posts
  • Last active: Nov 10 2007 07:30 PM
  • Joined: 17 May 2007
Tsss... :)
No can do since I want the floating point remainder.

Lexikos
  • Administrators
  • 9844 posts
  • AutoHotkey Foundation
  • Last active:
  • Joined: 17 Oct 2006
What floating point remainder?

Mod(Dividend, Divisor): Modulo. Returns the remainder when Dividend is divided by Divisor.

Mod(1.0,0.1)
1.0 / 0.1 = 10

No remainder...

Btw, you can redefine built-in functions.
mod(a, b) {
  return a - b * floor(a/b)
}
Obviously not as efficient as what AHK uses (qmathFmod(); 6 assembly instructions :shock:.)

JambaFun
  • Members
  • 7 posts
  • Last active: Nov 10 2007 07:30 PM
  • Joined: 17 May 2007

What floating point remainder?

Well, zero of course.

Mod(1.0,0.1) incorrectly returns 0.1.

Laszlo
  • Moderators
  • 4713 posts
  • Last active: Mar 31 2012 03:17 AM
  • Joined: 14 Feb 2005
This could be the old inexact floating point representation problem. Short decimal numbers have often infinite, periodic binary representations, which have to be truncated internally. Consequently, the results of arithmetic operations are also just approximate.
SetFormat Float, 0.20

MsgBox % Mod(1.0,0.1) ; 0.09999999999999995000
There is no bug here. You cannot always expect exact floating point results.

  • Guests
  • Last active:
  • Joined: --
thanks for the solution Lexikos...worked great for what i needed

Raccoon
  • Members
  • 178 posts
  • Last active: Oct 06 2014 05:58 PM
  • Joined: 02 Jan 2008
Strange. I don't know what to say about this.

Clearly, Mod(10,1) = 0, so Mod(1.0,0.1) should also result in 0. And yet, 3 other languages I've tested this in returns Mod(1.0,0.1) = 0.1, while most calculators return 0.

Consider Mod(0.3,0.2) should be 0.1, no? And that's what I get in those languages that support non-integer values, but Mod(1.0,0.1) just doesn't make sense for it to return 0.1. It's a mystery to me.

I'm going to ask in some #math IRC channels.
Posted Image

Need help right away? Get live support on IRC.
Already have an IRC client installed? /join #ahk

Laszlo
  • Moderators
  • 4713 posts
  • Last active: Mar 31 2012 03:17 AM
  • Joined: 14 Feb 2005
Read the posts above: you are asking the exact ratio of inexact numbers. If you perform fixpoint arithmetic, or BCD, your result will be different. Floats often are inexact, in any language.