Real, mathematical modulo operation in Postgres?
SELECT MOD(24 + MOD(-2, 24), 24);
will return 22 instead of -2
integer division in Ruby with negative value
This is how it is designed. Ruby rounds numbers towards negative infinity in case of negative division and modulo operation. This is not unique to Ruby, Python and Perl behaves like that also.
However, this approach provides a good mathematical reason.
a / b = q
with remainder r
such that
b * q + r = a and 0 <= r < b
From what I read, this is how arithmetic is taught in Japan.
Edit:
sawa pointed out that this is how positive arithmetic is taught in Japan, not negative numbers. However, as he said, this can be extended to negative numbers as well.
Sources:
Ruby Forums
Mod with negative numbers gives a negative result in Java and C
The %
operator is treated as a remainder operator, so the sign of the result is the same as that of the dividend.
If you want a modulo function, you can do something like this:
int mod(int a, int b)
{
int ret = a % b;
if (ret < 0)
ret += b;
return ret;
}
Related Topics
Rails Form Validation Conditional Bypass
Rails - Pass Id Parameter on a Link_To
How to Have Rspec Test for My Default Scope
How to Insert a String into a Textfile
Heroku App Crash H10 - Bash: Bin/Rails: No Such File or Directory
301 Moved Permanently After S3 Uploading
Chaining Methods Using Symbol#To_Proc Shorthand in Ruby
Removing a Model in Rails (Reverse of "Rails G Model Title...")
Ruby Ternary Operator Without Else
How to Ftp in Ruby Without First Saving the Text File
How to Use Gems Not in a Gemfile When Working with Bundler
How to Create a Nokogiri Case Insensitive Xpath Selector
Heroku: Gemfile.Lock Is Required Issue
Error: Failed to Build Gem Native Extension (Ruby Extconf.Rb): MAC Osx