What does the '%' operator mean? - c#

I have next code
int a,b,c;
b=1;
c=36;
a=b%c;
What does "%" operator mean?

It is the modulo (or modulus) operator:
The modulus operator (%) computes the remainder after dividing its first operand by its second.
For example:
class Program
{
static void Main()
{
Console.WriteLine(5 % 2); // int
Console.WriteLine(-5 % 2); // int
Console.WriteLine(5.0 % 2.2); // double
Console.WriteLine(5.0m % 2.2m); // decimal
Console.WriteLine(-5.2 % 2.0); // double
}
}
Sample output:
1
-1
0.6
0.6
-1.2
Note that the result of the % operator is equal to x – (x / y) * y and that if y is zero, a DivideByZeroException is thrown.
If x and y are non-integer values x % y is computed as x – n * y, where n is the largest possible integer that is less than or equal to x / y (more details in the C# 4.0 Specification in section 7.8.3 Remainder operator).
For further details and examples you might want to have a look at the corresponding Wikipedia article:
Modulo operation (on Wikipedia)

% is the remainder operator in many C-inspired languages.
3 % 2 == 1
789 % 10 = 9
It's a bit tricky with negative numbers. In e.g. Java and C#, the result has the same sign as the dividend:
-1 % 2 == -1
In e.g. C++ this is implementation defined.
See also
Wikipedia/Modulo operation
References
MSDN/C# Language Reference/% operator

That is the Modulo operator. It will give you the remainder of a division operation.

It's the modulus operator. That is, 2 % 2 == 0, 4 % 4 % 2 == 0 (2, 4 are divisible by 2 with 0 remainder), 5 % 2 == 1 (2 goes into 5 with 1 as remainder.)

It is the modulo operator. i.e. it the remainder after division 1 % 36 == 1 (0 remainder 1)

That is the modulo operator, which finds the remainder of division of one number by another.
So in this case a will be the remainder of b divided by c.

It's is modulus, but you example is not a good use of it. It gives you the remainder when two integers are divided.
e.g. a = 7 % 3 will return 1, becuase 7 divided by 3 is 2 with 1 left over.

It is modulus operator
using System;
class Test
{
static void Main()
{
int a = 2;
int b = 6;
int c = 12;
int d = 5;
Console.WriteLine(b % a);
Console.WriteLine(c % d);
Console.Read();
}
}
Output:
0
2

is basic operator available in almost every language and generally known as modulo operator.
it gives remainder as result.

Okay well I did know this till just trying on a calculator and playing around so basically:
5 % 2.2 = 0.6 is like saying on a calculator 5/2.2 = 2.27 then you multiply that .27 times the 2.27 and you round and you get 0.6. Hope this helps, it helped me =]

Nobody here has provided any examples of exactly how an equation can return different results, such as comparing 37/6 to 37%6, and before some of you get upset thinking that you did, pause for a moment and think about it for a minute, according to Dirk Vollmar in here the int x % int y parses as (x - (x / y) * y) which seems fairly straightforward at first glance, but not all Math is performed in the same order.
Since not every equation has it's proper brackets, some Schools will teach that the Equation is to be parsed as ((x - (x / y)) * y) whilst other Schools teach (x - ((x / y) * y)).
Now I experimented with my example (37/6 & 37%6) and figured out which selection was intended (it's (x - ((x / y) * y))), and I even displayed a nicely built if Loop (even though I forgot every End of Line Semicolon) to simulate the Divide Equation at the most Fundamental Scale, as that was in fact my point, the Equation is similar, yet Fundamentally different.
Here's what I can remember from my deleted Post (this took me around an Hour to Type from my Phone, indents are Double Spaced)
using System;
class Test
{
static void Main()
{
float exact0 = (37 / 6); //6.1666e∞
float exact1 = (37 % 6); //1
float exact2 = (37 - (37 / 6) * 6); //0
float exact3 = ((37 - (37 / 6)) * 6); //0
float exact4 = (37 - ((37 / 6) * 6)); //185
int a = 37;
int b = 6;
int c = 0;
int d = a;
int e = b;
string Answer0 = "";
string Answer1 = "";
string Answer2 = "";
string Answer0Alt = "";
string Answer1Alt = "";
string Answer2Alt = "";
Console.WriteLine("37/6: " + exact0);
Console.WriteLine("37%6: " + exact1);
Console.WriteLine("(37 - (37 / 6) * 6): " + exact2);
Console.WriteLine("((37 - (37 / 6)) * 6): " + exact3);
Console.WriteLine("(37 - ((37 / 6) * 6)): " + exact4);
Console.WriteLine("a: " + a + ", b: " + b + ", c: " + c + ", d: " + d + ", e: " + e);
Console.WriteLine("Answer0: " + Answer0);
Console.WriteLine("Answer0Alt: " + Answer0Alt);
Console.WriteLine("Answer1: " + Answer1);
Console.WriteLine("Answer0Alt: " + Answer1Alt);
Console.WriteLine("Answer2: " + Answer2);
Console.WriteLine("Answer2Alt: " + Answer2Alt);
Console.WriteLine("Init Complete, starting Math...");
Loop
{
if (a !< b) {
a - b;
c +1;}
if else (a = b) {
a - b;
c +1;}
else
{
String Answer0 = c + "." + a; //6.1
//this is = to 37/6 in the fact that it equals 6.1 ((6*6=36)+1=37) or 6 remainder 1,
//which according to my Calculator App is technically correct once you Round Down the .666e∞
//which has been stated as the default behavior of the C# / Operand
//for completion sake I'll include the alternative answer for Round Up also
String Answer0Alt = c + "." + (a + 1); //6.2
Console.WriteLine("Division Complete, Continuing...");
Break
}
}
string Answer1 = ((d - (Answer0)) * e); //185.4
string Answer1Alt = ((d - (Answer0Alt​)) * e); // 184.8
string Answer2 = (d - ((Answer0) * e)); //0.4
string Answer2Alt = (d - ((Answer0Alt​) * e)); //-0.2
Console.WriteLine("Math Complete, Summarizing...");
Console.WriteLine("37/6: " + exact0);
Console.WriteLine("37%6: " + exact1);
Console.WriteLine("(37 - (37 / 6) * 6): " + exact2);
Console.WriteLine("((37 - (37 / 6)) * 6): " + exact3);
Console.WriteLine("(37 - ((37 / 6) * 6)): " + exact4);
Console.WriteLine("Answer0: " + Answer0);
Console.WriteLine("Answer0Alt: " + Answer0Alt);
Console.WriteLine("Answer1: " + Answer1);
Console.WriteLine("Answer0Alt: " + Answer1Alt);
Console.WriteLine("Answer2: " + Answer2);
Console.WriteLine("Answer2Alt: " + Answer2Alt);
Console.Read();
}
}
This also CLEARLY demonstrated how an outcome can be different for the exact same Equation.

Related

How would i work out magnitude quickly for 3 values?

How can I use a Fast Magnitude calculation for 3 values (instead of using square root)? (+/- 3% is good enough)
public void RGBToComparison(Color32[] color)
{
DateTime start = DateTime.Now;
foreach (Color32 i in color)
{
var r = PivotRgb(i.r / 255.0);
var g = PivotRgb(i.g / 255.0);
var b = PivotRgb(i.b / 255.0);
var X = r * 0.4124 + g * 0.3576 + b * 0.1805;
var Y = r * 0.2126 + g * 0.7152 + b * 0.0722;
var Z = r * 0.0193 + g * 0.1192 + b * 0.9505;
var LB = PivotXyz(X / 95.047);
var AB = PivotXyz(Y / 100);
var BB = PivotXyz(Z / 108.883);
var L = Math.Max(0, 116 * AB - 16);
var A = 500 * (LB - AB);
var B = 200 * (AB - BB);
totalDifference += Math.Sqrt((L-LT)*(L-LT) + (A-AT)*(A-AT) + (B-BT)*(B-BT));
}
totalDifference = totalDifference / color.Length;
text.text = "Amount of Pixels: " + color.Length + " Time(MilliSeconds):" + DateTime.Now.Subtract(start).TotalMilliseconds + " Score (0 to 100)" + (totalDifference).ToString();
RandomOrNot();
}
private static double PivotRgb(double n)
{
return (n > 0.04045 ? Math.Pow((n + 0.055) / 1.055, 2.4) : n / 12.92) * 100.0;
}
private static double PivotXyz(double n)
{
return n > 0.008856 ? CubicRoot(n) : (903.3 * n + 16) / 116;
}
private static double CubicRoot(double n)
{
return Math.Pow(n, 1.0 / 3.0);
}
This is the important part: totalDifference += Math.Sqrt((L-LT)*(L-LT) + (A-AT)*(A-AT) + (B-BT)*(B-BT));
I know there are FastMagnitude calculations online, but all the ones online are for two values, not three. For example, could i use the difference between the values to get a precise answer? (By implementing the difference value into the equation, and if the difference percentage-wise is big, falling back onto square root?)
Adding up the values and iterating the square root every 4 pixels is a last resort that I could do. But firstly, I want to find out if it is possible to have a good FastMagnitude calculation for 3 values.
I know I can multi-thread and parllelize it, but I want to optimize my code before I do that.
If you just want to compare the values, why not leave the square root out and work with the length squared?
Or use the taylor series of the square root of 1+x and cut off early :)

Why this sin(x) function in C# return NaN instead of a number

I have this function wrote in C# to calc the sin(x). But when I try with x = 3.14, the printed result of sin X is NaN (not a number),
but when debugging, its is very near to 0.001592653
The value is not too big, neither too small. So how could the NaN appear here?
static double pow(double x, int mu)
{
if (mu == 0)
return 1;
if (mu == 1)
return x;
return x * pow(x, mu - 1);
}
static double fact(int n)
{
if (n == 1 || n == 0)
return 1;
return n * fact(n - 1);
}
static double sin(double x)
{
var s = x;
for (int i = 1; i < 1000; i++)
{
s += pow(-1, i) * pow(x, 2 * i + 1) / fact(2 * i + 1);
}
return s;
}
public static void Main(String[] param)
{
try
{
while (true)
{
Console.WriteLine("Enter x value: ");
double x = double.Parse(Console.ReadLine());
var sinX = sin(x);
Console.WriteLine("Sin of {0} is {1}: " , x , sinX);
Console.ReadLine();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
It fails because both pow(x, 2 * i + 1) and fact(2 * i + 1) eventually return Infinity.
In my case, it's when x = 4, i = 256.
Note that pow(x, 2 * i + 1) = 4 ^ (2 * 257) = 2.8763090157797054523668883052624395737887631663 × 10^309 - a stupidly large number which is just over the max value of a double, which is approximately 1.79769313486232 x 10 ^ 308.
You might be interested in just using Math.Sin(x)
Also note that fact(2 * i + 1) = 513! =an even more ridiculously large number which is more than 10^1000 times larger than the estimated number of atoms in the observable universe.
When x == 3.14 and i == 314 then you get Infinity:
?pow(-1, 314)
1.0
?pow(x, 2 * 314 + 1)
Infinity
? fact(2 * 314 + 1)
Infinity
The problem here is an understanding of floating point representation of 'real' numbers.
Double numbers while allowing a large range of values only has a precision of 15 to 17 decimal digits.
In this example we are calculating a value between -1 and 1.
We calculate the value of the sin function by using the series expansion of it which is basically a the sum of terms. In that expansion the terms become smaller and smaller as we go along.
When the terms have reached a value less than 1e-17 adding them to what is already there will not make any difference. This is so because we only have 52 bit of precision which are used up by the time we get to a term of less than 1e-17.
So instead of doing a constant 1000 loops you should do something like this:
static double sin(double x)
{
var s = x;
for (int i = 1; i < 1000; i++)
{
var term = pow(x, 2 * i + 1) / fact(2 * i + 1);
if (term < 1e-17)
break;
s += pow(-1, i) * term;
}
return s;
}

x++ operator for playing gif animations: How do it work together in this example? [duplicate]

I have next code
int a,b,c;
b=1;
c=36;
a=b%c;
What does "%" operator mean?
It is the modulo (or modulus) operator:
The modulus operator (%) computes the remainder after dividing its first operand by its second.
For example:
class Program
{
static void Main()
{
Console.WriteLine(5 % 2); // int
Console.WriteLine(-5 % 2); // int
Console.WriteLine(5.0 % 2.2); // double
Console.WriteLine(5.0m % 2.2m); // decimal
Console.WriteLine(-5.2 % 2.0); // double
}
}
Sample output:
1
-1
0.6
0.6
-1.2
Note that the result of the % operator is equal to x – (x / y) * y and that if y is zero, a DivideByZeroException is thrown.
If x and y are non-integer values x % y is computed as x – n * y, where n is the largest possible integer that is less than or equal to x / y (more details in the C# 4.0 Specification in section 7.8.3 Remainder operator).
For further details and examples you might want to have a look at the corresponding Wikipedia article:
Modulo operation (on Wikipedia)
% is the remainder operator in many C-inspired languages.
3 % 2 == 1
789 % 10 = 9
It's a bit tricky with negative numbers. In e.g. Java and C#, the result has the same sign as the dividend:
-1 % 2 == -1
In e.g. C++ this is implementation defined.
See also
Wikipedia/Modulo operation
References
MSDN/C# Language Reference/% operator
That is the Modulo operator. It will give you the remainder of a division operation.
It's the modulus operator. That is, 2 % 2 == 0, 4 % 4 % 2 == 0 (2, 4 are divisible by 2 with 0 remainder), 5 % 2 == 1 (2 goes into 5 with 1 as remainder.)
It is the modulo operator. i.e. it the remainder after division 1 % 36 == 1 (0 remainder 1)
That is the modulo operator, which finds the remainder of division of one number by another.
So in this case a will be the remainder of b divided by c.
It's is modulus, but you example is not a good use of it. It gives you the remainder when two integers are divided.
e.g. a = 7 % 3 will return 1, becuase 7 divided by 3 is 2 with 1 left over.
It is modulus operator
using System;
class Test
{
static void Main()
{
int a = 2;
int b = 6;
int c = 12;
int d = 5;
Console.WriteLine(b % a);
Console.WriteLine(c % d);
Console.Read();
}
}
Output:
0
2
is basic operator available in almost every language and generally known as modulo operator.
it gives remainder as result.
Okay well I did know this till just trying on a calculator and playing around so basically:
5 % 2.2 = 0.6 is like saying on a calculator 5/2.2 = 2.27 then you multiply that .27 times the 2.27 and you round and you get 0.6. Hope this helps, it helped me =]
Nobody here has provided any examples of exactly how an equation can return different results, such as comparing 37/6 to 37%6, and before some of you get upset thinking that you did, pause for a moment and think about it for a minute, according to Dirk Vollmar in here the int x % int y parses as (x - (x / y) * y) which seems fairly straightforward at first glance, but not all Math is performed in the same order.
Since not every equation has it's proper brackets, some Schools will teach that the Equation is to be parsed as ((x - (x / y)) * y) whilst other Schools teach (x - ((x / y) * y)).
Now I experimented with my example (37/6 & 37%6) and figured out which selection was intended (it's (x - ((x / y) * y))), and I even displayed a nicely built if Loop (even though I forgot every End of Line Semicolon) to simulate the Divide Equation at the most Fundamental Scale, as that was in fact my point, the Equation is similar, yet Fundamentally different.
Here's what I can remember from my deleted Post (this took me around an Hour to Type from my Phone, indents are Double Spaced)
using System;
class Test
{
static void Main()
{
float exact0 = (37 / 6); //6.1666e∞
float exact1 = (37 % 6); //1
float exact2 = (37 - (37 / 6) * 6); //0
float exact3 = ((37 - (37 / 6)) * 6); //0
float exact4 = (37 - ((37 / 6) * 6)); //185
int a = 37;
int b = 6;
int c = 0;
int d = a;
int e = b;
string Answer0 = "";
string Answer1 = "";
string Answer2 = "";
string Answer0Alt = "";
string Answer1Alt = "";
string Answer2Alt = "";
Console.WriteLine("37/6: " + exact0);
Console.WriteLine("37%6: " + exact1);
Console.WriteLine("(37 - (37 / 6) * 6): " + exact2);
Console.WriteLine("((37 - (37 / 6)) * 6): " + exact3);
Console.WriteLine("(37 - ((37 / 6) * 6)): " + exact4);
Console.WriteLine("a: " + a + ", b: " + b + ", c: " + c + ", d: " + d + ", e: " + e);
Console.WriteLine("Answer0: " + Answer0);
Console.WriteLine("Answer0Alt: " + Answer0Alt);
Console.WriteLine("Answer1: " + Answer1);
Console.WriteLine("Answer0Alt: " + Answer1Alt);
Console.WriteLine("Answer2: " + Answer2);
Console.WriteLine("Answer2Alt: " + Answer2Alt);
Console.WriteLine("Init Complete, starting Math...");
Loop
{
if (a !< b) {
a - b;
c +1;}
if else (a = b) {
a - b;
c +1;}
else
{
String Answer0 = c + "." + a; //6.1
//this is = to 37/6 in the fact that it equals 6.1 ((6*6=36)+1=37) or 6 remainder 1,
//which according to my Calculator App is technically correct once you Round Down the .666e∞
//which has been stated as the default behavior of the C# / Operand
//for completion sake I'll include the alternative answer for Round Up also
String Answer0Alt = c + "." + (a + 1); //6.2
Console.WriteLine("Division Complete, Continuing...");
Break
}
}
string Answer1 = ((d - (Answer0)) * e); //185.4
string Answer1Alt = ((d - (Answer0Alt​)) * e); // 184.8
string Answer2 = (d - ((Answer0) * e)); //0.4
string Answer2Alt = (d - ((Answer0Alt​) * e)); //-0.2
Console.WriteLine("Math Complete, Summarizing...");
Console.WriteLine("37/6: " + exact0);
Console.WriteLine("37%6: " + exact1);
Console.WriteLine("(37 - (37 / 6) * 6): " + exact2);
Console.WriteLine("((37 - (37 / 6)) * 6): " + exact3);
Console.WriteLine("(37 - ((37 / 6) * 6)): " + exact4);
Console.WriteLine("Answer0: " + Answer0);
Console.WriteLine("Answer0Alt: " + Answer0Alt);
Console.WriteLine("Answer1: " + Answer1);
Console.WriteLine("Answer0Alt: " + Answer1Alt);
Console.WriteLine("Answer2: " + Answer2);
Console.WriteLine("Answer2Alt: " + Answer2Alt);
Console.Read();
}
}
This also CLEARLY demonstrated how an outcome can be different for the exact same Equation.

Dealing with large integers without BigInteger Library in Algorithm contests

Problem: Topcoder SRM 170 500
Consider a sequence {x0, x1, x2, ...}. A relation that defines some term xn in terms of previous terms is called a recurrence relation. A linear recurrence relation is one where the recurrence is of the form xn = c(k-1) * x(n-1) + c(k-2) * x(n-2) + ... + c(0) * x(n-k)
where all the c(i) are real-valued constants, k is the length of the recurrence relation, and n is an arbitrary positive integer which is greater than or equal to k.
You will be given a int[] coefficients, indicating, in order, c(0), c(1), ..., c(k-1). You will also be given a int[] initial, giving the values of x(0), x(1), ..., x(k-1), and an int N. Your method should return xN modulo 10.
More specifically, if coefficients is of size k, then the recurrence relation will be
xn = coefficients[k - 1] * xn-1 + coefficients[k - 2] * xn-2 + ... + coefficients[0] * xn-k.
For example, if coefficients = {2,1}, initial = {9,7}, and N = 6, then our recurrence relation is xn = xn-1 + 2 * xn-2 and we have x0 = 9 and x1 = 7. Then x2 = x1 + 2 * x0 = 7 + 2 * 9 = 25, and similarly, x3 = 39, x4 = 89, x5 = 167, and x6 = 345, so your method would return (345 modulo 10) = 5.
Constraints:
- Code must run in less than or equal to 2 seconds
- Memory utilization must not exceed 64 MB
My attempted Solution:
class RecurrenceRelation
{
public int moduloTen(int[] coefficients, int[] initial, int N)
{
double xn = 0; int j = 0;
int K = coefficients.Length;
List<double> xs = new List<double>(Array.ConvertAll<int, double>(initial,
delegate(int i)
{
return (double)i;
}));
if (N < K)
return negativePositiveMod(xs[N]);
while (xs.Count <= N)
{
for (int i = xs.Count - 1; i >= j; i--)
{
xn += xs[i] * coefficients[K--];
}
K = coefficients.Length;
xs.Add(xn);
xn = 0;
j++;
}
return negativePositiveMod(xs[N]);
}
public int negativePositiveMod(double b)
{
while (b < 0)
{
b += 10;
}
return (int)(b % 10);
}
}
My problem with this solution is the precision of the double representation, and since I can't use a third party library or the BigInteger library in .NET for this SRM, i need to find a way of solving it without them. I suspect I could use recursion but I'm a little clueless on how to go about that.
Here is a test case that shows when my code works and when it doesn't
{2,1}, {9,7}, 6 - Successfully returns 5
{9,8,7,6,5,4,3,2,1,0}, {1,2,3,4,5,6,7,8,9,10}, 654 - Unsuccessfully returns 8 instead of 5 due to precision of double type
Can anyone help me figure this out? I was going to consider using arrays to store the values but it is a little bit beyond me especially on how to cater for multiplication and still be within the time and space complexity set out in the problem. Perhaps my entire approach is wrong? I'd appreciate some pointers and direction (not fully fleshed out answers) answers please.
Thanks
Notice that we only need to return the modulo 10 of xn.
We also need to know that if a = b + c, we have a % 10 = (b % 10 + c % 10) %10.
And a = b*c, so we also have a % 10 = (b %10 * c % 10) % 10;
So, for
xn = c(k-1) * x(n-1) + c(k-2) * x(n-2) + ... + c(0) * x(n-k)
= a0 + a1 + .... + an
(with a0 = c(k - 1)*x(n-1), a1 = ...)
we have xn % 10 = (a0 % 10 + a1 % 10 + ...)%10
And for each ai = ci*xi, so ai % 10 = (ci % 10 * xi % 10)% 10.
So by doing all of these math calculations, we can avoid to use double and keep the result in manageable size.
As Pham has answered, the trick is to realize that you only need to return a modulo, thereby bypassing the problem of overflow. Here is my quick attempt. I use a queue to put in the last result xN, and evict the oldest one.
static int solve(int[] coefficients, int[] seed, int n)
{
int k = coefficients.Count();
var queue = new Queue<int>(seed.Reverse().Take(k).Reverse());
for (int i = k; i <= n; i++)
{
var xn = coefficients.Zip(queue, (x, y) => x * y % 10).Sum() % 10;
queue.Enqueue(xn);
queue.Dequeue();
}
return (int) (queue.Last() );
}
Edit:
Getting the same results as you expect, however I don't guarantee that there is no bug in this example.

Convert Code to C#

I was looking into random number generators and found pseudo code for one:
function Noise1(integer x)
x = (x<<13) ^ x;
return ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0);
end function
I would like to convert this into C# but I get all kinds of error like invalid expressions and ")" expected. This is what I have so far how can I convert it?
double Noise(int x) {
x = (x<<13) ^ x;
return ( 1.0 - ((x * (x * x * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0);
}
Thanks.
I don't know what language you've started with, but in C# hex constants should look differently: change 7fffffff to 0x7fffffff.
You can use the .Net Framework random object
Random rng = new Random();
return rng.Next(10)
But I strongly recommend you to read this article from Jon Skeet about random generators
http://csharpindepth.com/Articles/Chapter12/Random.aspx
EDIT: tested and reported a non-null sequence
Convert your hexadecimal constants to use "0x" prefix
Convert int <-> double carefully
Split the expression to make it a little bit more readable
Here's the code and unit test (strange results though):
using System;
namespace Test
{
public class Test
{
public static Int64 Noise(Int64 x) {
Int64 y = (Int64) ( (x << 13) ^ x);
Console.WriteLine(y.ToString());
Int64 t = (y * (y * y * 15731 + 789221) + 1376312589);
Console.WriteLine(t.ToString());
Int64 c = t < 0 ? -t : t; //( ((Int32)t) & 0x7fffffff);
Console.WriteLine("c = " + c.ToString());
double b = ((double)c) / 1073741824.0;
Console.WriteLine("b = " + b.ToString());
double t2 = ( 1.0 - b);
return (Int64)t2;
}
static void Main()
{
Int64 Seed = 1234;
for(int i = 0 ; i < 3 ; i++)
{
Seed = Noise(Seed);
Console.WriteLine(Seed.ToString());
}
}
}
}

Categories