Mathematical modulus in c# - c#

Is there a library function in c# for the mathematical modulus of a number - by this I specifically mean that a negative integer modulo a positive integer should yield a positive result.
edited to provide an example:
-5 modulo 3 should return 1

Try (a % b) * Math.Sign(a)
Try this; it works correctly.
static int MathMod(int a, int b) {
return (Math.Abs(a * b) + a) % b;
}

x < 0 ? ((x % m) + m) % m : x % m;

Well the definition (if I'm not mistaken) is something like this
a mod b = a - b * floor(a/b)
It's probably pretty slow and beware of integer division just like built in modulus :)
Other option is to modify the result of built-in modulus according to the signs of operands. Something like this:
if(a < 0 && b > 0)
{
return (a % b + b) % b;
}
else if ....

a < 0 ? ((a+1)%b + b-1) : (a%b);
That requires only one % operation (and one ternary op) and no multiplication

If you're using any of these algorithms and you need to do division also, don't forget to make sure that you subtract 1 when appropriate.
I.e.,
if -5 % 2 = -1 and -5 / 2 = -2, and if you care that -5 / 2 * 2 + -5 % 2 = -5, then when you calculate -5 % 2 = 1, that you also calculate -5 / 2 = -3.

Fix :
(ans=a%b)<0 ? (a<0 && b<0 ? (ans-b)%(-b) : (ans+b)%b) : ans

I know the question didn't ask for it, but I just wrote and tested a method which returns the quotient as well. Didn't find this when I was looking for it, so I thought I'd put it out there.
/// <summary>
/// Compute integer quotient and remainder of <paramref name="dividend"/> / <paramref name="divisor"/>
/// where the <paramref name="remainder"/> has the same sign as <paramref name="divisor"/>, and is
/// between zero (inclusive) and the <paramref name="divisor"/> (exclusive). As always,
/// (quotientResult * <paramref name="divisor"/> + <paramref name="remainder"/> == <paramref name="dividend"/>).
/// </summary>
public static int DivRemPeriodic(int dividend, int divisor, out int remainder) {
var quotient = Math.DivRem(dividend, divisor, out remainder);
if (divisor > 0 ? remainder < 0 : remainder > 0) {
remainder += divisor;
quotient -= 1;
}
return quotient;
}

Might be the % operator?
http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx

Related

How can I write a symmetrical version of a snap to value formula (in C#)

I would like to write a component that can move a value up by an increment amount, or move to the nearest increment.
Assuming the increment was 0.0005, for an Up() method, here would be the expected inputs and outputs:
1.0005 -> 1.0010 (at increment so it moves by the increment)
1.0006 -> 1.0010 (not at increment, so moves to increment)
1.0007 -> 1.0010
1.0008 -> 1.0010
1.0009 -> 1.0010
1.0010 -> 1.0015 (at increment so it moves by the increment)
1.0011 -> 1.0015
1.0012 -> 1.0015
etc
And the Down() method would do the same, in reverse.
I have come up with this formula for up:
return (value + increment) - (value % increment);
I expected that the Down() method would be similar but I can't find what it is. The only way I've been able to get it to work is by doing:
decimal mod = value % increment;
return mod != 0 ? value - mod : value - increment
Surely if the operation is the same in reverse, then the formulas should be the same.
public static decimal Increment(decimal dec, decimal inc) {
var mod = (dec % inc);
return dec - Math.Abs(mod) + (inc < 0 && mod != 0 ? Math.Abs(inc) : 0) + inc;
}
Without the ternary operator:
public static decimal Increment(decimal dec, decimal inc) {
var mod = (dec % inc);
var signInc = Math.Sign(inc);
return dec - Math.Abs(mod) +
((decimal)(Math.Pow(signInc, 2) - signInc) / 2) *
Math.Abs(Math.Sign(mod)) *
Math.Abs(inc)
+ inc;
}
((decimal)(Math.Pow(signInc, 2) - signInc) / 2) *
Math.Abs(Math.Sign(mod)) *
Math.Abs(inc)
replaces the ternary expression. Math.Pow(signInc, 2) - signInc) / 2 returns 1 if inc is negative and 0 otherwise. Math.Abs(Math.Sign(mod)) returns 0 if mod is 0 and 1 otherwise; making the result of the first multiplication 1 if inc < 0 && mod != 0 and 0 otherwise.
formula
value - Abs(value % increment) + Abs(increment/2) + increment/2
take value 1.0006 as example with increment (+_)0.0005
when up increment is +0.0005
1.0006-0.0001+0.00025+0.00025 = 1.0010
when down increment is -0.0005
1.0006-0.0001+0.00025-0.00025 = 1.0005

Rounding integers to nearest multiple of 10 [duplicate]

This question already has answers here:
Returning the nearest multiple value of a number
(6 answers)
Closed 3 years ago.
I am trying to figure out how to round prices - both ways. For example:
Round down
43 becomes 40
143 becomes 140
1433 becomes 1430
Round up
43 becomes 50
143 becomes 150
1433 becomes 1440
I have the situation where I have a price range of say:
£143 - £193
of which I want to show as:
£140 - £200
as it looks a lot cleaner
Any ideas on how I can achieve this?
I would just create a couple methods;
int RoundUp(int toRound)
{
if (toRound % 10 == 0) return toRound;
return (10 - toRound % 10) + toRound;
}
int RoundDown(int toRound)
{
return toRound - toRound % 10;
}
Modulus gives us the remainder, in the case of rounding up 10 - r takes you to the nearest tenth, to round down you just subtract r. Pretty straight forward.
You don't need to use modulus (%) or floating point...
This works:
public static int RoundUp(int value)
{
return 10*((value + 9)/10);
}
public static int RoundDown(int value)
{
return 10*(value/10);
}
This code rounds to the nearest multiple of 10:
int RoundNum(int num)
{
int rem = num % 10;
return rem >= 5 ? (num - rem + 10) : (num - rem);
}
Very simple usage :
Console.WriteLine(RoundNum(143)); // prints 140
Console.WriteLine(RoundNum(193)); // prints 190
A general method to round a number to a multiple of another number, rounding away from zero.
For integer
int RoundNum(int num, int step)
{
if (num >= 0)
return ((num + (step / 2)) / step) * step;
else
return ((num - (step / 2)) / step) * step;
}
For float
float RoundNum(float num, float step)
{
if (num >= 0)
return floor((num + step / 2) / step) * step;
else
return ceil((num - step / 2) / step) * step;
}
I know some parts might seem counter-intuitive or not very optimized. I tried casting (num + step / 2) to an int, but this gave wrong results for negative floats ((int) -12.0000 = -11 and such). Anyways these are a few cases I tested:
any number rounded to step 1 should be itself
-3 rounded to step 2 = -4
-2 rounded to step 2 = -2
3 rounded to step 2 = 4
2 rounded to step 2 = 2
-2.3 rounded to step 0.2 = -2.4
-2.4 rounded to step 0.2 = -2.4
2.3 rounded to step 0.2 = 2.4
2.4 rounded to step 0.2 = 2.4
Divide the number by 10.
number = number / 10;
Math.Ceiling(number);//round up
Math.Round(number);//round down
Then multiply by 10.
number = number * 10;
public static int Round(int n)
{
// Smaller multiple
int a = (n / 10) * 10;
// Larger multiple
int b = a + 10;
// Return of closest of two
return (n - a > b - n) ? b : a;
}

What does % mean in C#?

Sorry for a possible repeat question the % symbol doesn't coincide with searchability.
What does % mean? I can't seem to stick this one down.
Example:
rotation = value % MathHelper.TwoPi;
is a specific instance.
But I have found code that uses % more often. Modulus I 'think' it is called, but I am not positive.
Previous Post:
With well thought out awnser
% Operator (C# Reference)
The % operator computes the remainder after dividing its first operand
by its second. All numeric types have predefined remainder operators.
See MSDN:
C# Operators
% Operator (C# Reference)
It is the modulus operator. It computes the remainder after dividing its first operand by its second, e.g.
5 % 2 = 1
6 % 2 = 0
5 % 3 = 2.
in C# it means modulus, which is basically a remainder of
example:
int remainder = 10 % 3 //remainder is 1
It is the modulus operator. It returns the remainder of an integer.
int remainder = 2 % 1; // (remainder variable is assigned to 0)
int remainder2 = 3 % 2; // (remainder variable is assigned to 1)
Yes it' the modulus.
http://en.wikipedia.org/wiki/Modulus_(algebraic_number_theory)
Let's say that
x / y = z,
x, y, z being integers.
There is no guarantee that
z * y = x, because the "/" operator rounds down.
So we must add a remainder to our equation:
z * y = x + r.
z * y = x + r
z * (-y) = - (z * y) = -(x + r) = -x - r
This means that the result of the "%" operator can be negative, which means that the "%" or remainder operator differs from the modulo relation, because the result is not guaranteed to be canonical.

% (mod) explanation

Today I was writing a program in C#, and I used % to calculate some index... My program didn't work, so I debugged it and I realized that "%" is not working like in other program languages that I know.
For example:
In Python % returns values like this:
for x in xrange (-5, 6):
print x, "% 5 =", x % 5
-5 % 5 = 0
-4 % 5 = 1
-3 % 5 = 2
-2 % 5 = 3
-1 % 5 = 4
0 % 5 = 0
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0
In C#:
for (int i = -5; i < 6; i++)
{
Console.WriteLine(i + " % 5 = " + i % 5);
}
-5 % 5 = 0
-4 % 5 = -4
-3 % 5 = -3
-2 % 5 = -2
-1 % 5 = -1
0 % 5 = 0
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0
Did I do something wrong or is % not working like it should?
As explained in the comments, the different behaviour is by design. The different languages just ascribe different meanings to the % operator.
You ask:
How can I use modulus operator in C#?
You can define a modulus operator yourself that behaves the same way as the Python % operator:
int mod(int a, int n)
{
int result = a % n;
if ((result<0 && n>0) || (result>0 && n<0)) {
result += n;
}
return result;
}
Both answers are correct. Although personally I think the "always positive" one makes more sense.
You can define your own modulus function that only gives positive answers like this:
int mod(int a, int n) {
return ((a%n)+n) % n;
}
In modular arithmetic, one defines classes of numbers based on the modulo. In other words, in modulo m arithmetic, a number n is equivalent (read: the same) to n + m, n - m, n + 2m, n - 2m, etc.
One defines m "baskets" and every number falls in one (and only one) of them.
Example: one can say "It's 4:30 pm" or one can say "It's 16:30". Both forms mean exactly the same time, but are different representations of it.
Thus both, the Python and C# results are correct! The numbers are the same in the modulo 5 arithmetic you chose. It would also have been mathematically correct to return (5, 6, 7, 8, 9) for example. Just a bit odd.
As for the choice of representation (in other words, the choice on how to represent negative numbers), that is just a case of different design choices between the two languages.
However, that is not at all what the % operator actually does in C#. The % operator is not the canonical modulus operator; it is the remainder operator. The A % B operator actually answer the question "If I divided A by B using integer arithmetic, what would the remainder be?"
— What's the difference? Remainder vs Modulus by Eric Lippert
Quick snippet to get the canonical modulus:
return ((n % m) + m) % m;
Test implementation:
Mono/C#:
machine:~ user$ cat mod.cs
using System;
public class Program
{
public static void Main (string[] args)
{
Console.WriteLine(Mod(-2, 5));
Console.WriteLine(Mod(-5, 5));
Console.WriteLine(Mod(-2, -5));
}
public static int Mod (int n, int m)
{
return ((n % m) + m) % m;
}
}
machine:~ user$ mono mod.exe
3
0
-2
Python:
machine:~ user$ cat mod.py
print -2%5;
print -5%5;
print -2%-5;
machine:~ user$ python mod.py
3
0
-2

How do you calculate if a number is a multiple of another number(well sort of)

pls, I HAVE A NUMBER say 9 and i want to find how to create a program to check if a number b is maybe 21(ie 9+12) or 33(ie 9 + 24) or 45(9 + 36) and so on. Can i get it in C# or SQL
With the clarification, it looks like you want to find whether there is an integer x for which (in math terms, not code)
b = 9 + 12x
is true; so you want to know whether b-9 is some multiple of 12; which is easy:
bool isMatch = ((b - 9) % 12) == 0;
and if you want to know which x:
int x = (b - 9) / 12;
It's not entirely clear from your question, but I think you're looking for the modulo operator. 21 % 12 = 9, 33 % 12 = 9, 45 % 12 = 9.
In C# and SQL this is just %, and it is used like an arithmetic operator (+, -, etc)
I think you've got three variables and than the solution will be like this:
var a = 9;
var b = 12;
var c = 21;
var isInRange = IsInRange(c, a, b);
private bool IsInRange(int input, int offset, int multiple){
return ((input - offset) % multiple) == 0;
}
Subtract your original number (in this case 9) from the number B, and then see if B % 12 is different from zero.

Categories

Resources