Having trouble in finding roots of a cubic equation with C# - c#

Recently my friends and I decided to make a multi-functional calculator to automatically find
the roots of quadratic equations.
It wasn't that challenging after all, so we decided to go onto the next level, to make a calculator for a cubic equation.
(ax^3 + bx^2 + cx + d)
However, we stumbled across some trivial problems, and no matter how hard we tried, the results are still the same.
we are beginners in terms of coding, so we're not sure if we are actually making some stupid mistakes here
but at least we want to learn something from others.
Basically, we have tried a lot of combinations of different cubic equations, or even re-coding the whole thing. The problem is that the results we yield are always wrong, but only for the real parts of the second root and third root.
For a better understanding, we have tried 9x^3 + 8x^2 + 7x + 6, as an example.
The correct answer, according to a cubic equation calculator website, is
(The website)
First root = -0.87285
Second root = -0.00802 + 0.87391 i
Third root = -0.00802 - 0.87391 i
However, our result to this equation is :
First root = -0.87285
Second root = -0.2963 + 0.87391 i
Third root = -0.2963 + -0.87391 i
It is apparently noticeable that only parts of the second and third roots are wrong.
We have tried finding similar threads to help, but those are a little bit too difficult for us to understand or those problems are not the same as ours.
We look forward to finding the solution and the causes to this problem.
We have separated the formulas for finding the roots of a cubic equation into 5 parts.
(rootp1-rootp5)
The formulas are coded according to the formulas that can be found in the Chinese version of Wikipedia's page of Cubic equation.
(The formulas)
We have also rounded the real parts of the roots to 5 digits.
(Some code lines might be redundant, but as I have mentioned, we are new to coding)
Code (C#) :
using System;
using System.Numerics;
namespace ComplexNumbers
{
public class ComplexNo
{
public static void Main()
{
Console.WriteLine("Cubic Equation Calculator :");
Console.Write("Insert first coefficient : ");
double a = Convert.ToDouble(Console.ReadLine());
Console.Write("Insert second coefficient : ");
double b = Convert.ToDouble(Console.ReadLine());
Console.Write("Insert third coefficient : ");
double c = Convert.ToDouble(Console.ReadLine());
Console.Write("Insert constant : ");
double d = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(" ");
Console.WriteLine("Solve for " + a + "x" + "^3 " + b + "x^2 " + c + "x " + d + " :");
double rootp1 = -(b / (3 * a));
double rootp2 = (b * c / (6 * Math.Pow(a, 2))) - (Math.Pow(b, 3) / (27 * Math.Pow(a, 3))) - (d / (2 * a));
double rootp3 = (c / (3 * a)) - (Math.Pow(b, 2) / (9 * Math.Pow(a, 2)));
Complex root1 = rootp1 + Math.Cbrt(rootp2 + Math.Sqrt(Math.Pow(rootp2, 2) + Math.Pow(rootp3, 3))) +
Math.Cbrt(rootp2 - Math.Sqrt(Math.Pow(rootp2, 2) + Math.Pow(rootp3, 3)));
Complex rootp4 = new Complex(-1 / 2, Math.Sqrt(3) / 2);
Complex rootp5 = new Complex(-1 / 2, -(Math.Sqrt(3) / 2));
Complex root2 = rootp1 + (rootp4 * Math.Cbrt(rootp2 + Math.Sqrt(Math.Pow(rootp2, 2) + Math.Pow(rootp3, 3)))) +
(rootp5 * Math.Cbrt(rootp2 - Math.Sqrt(Math.Pow(rootp2, 2) + Math.Pow(rootp3, 3))));
Complex root3 = rootp1 + (rootp5 * Math.Cbrt(rootp2 + Math.Sqrt(Math.Pow(rootp2, 2) + Math.Pow(rootp3, 3)))) +
(rootp4 * Math.Cbrt(rootp2 - Math.Sqrt(Math.Pow(rootp2, 2) + Math.Pow(rootp3, 3))));
Console.WriteLine(" ");
Console.WriteLine("Results :");
Console.WriteLine("First Root :");
string root1rp = Convert.ToString(Math.Round(root1.Real, 5));
string root1ip = Convert.ToString(Math.Round(root1.Imaginary, 5));
Console.WriteLine(root1rp + " + " + root1ip + "i");
Console.WriteLine("Second Root :");
string root2rp = Convert.ToString(Math.Round(root2.Real, 5));
string root2ip = Convert.ToString(Math.Round(root2.Imaginary, 5));
Console.WriteLine(root2rp + " + " + root2ip + "i");
Console.WriteLine("Third Root :");
string root3rp = Convert.ToString(Math.Round(root3.Real, 5));
string root3ip = Convert.ToString(Math.Round(root3.Imaginary, 5));
Console.WriteLine(root3rp + " + " + root3ip + "i");
Console.ReadLine();
}
}
}
(Sorry for making this thread so long and my bad grammar)

The problem is with this line Complex rootp4 = new Complex(-1 / 2, Math.Sqrt(3) / 2);. -1/2 uses integer division and evaluates to 0.
This code will work.
Console.WriteLine(" ");
Console.WriteLine("Solve for " + a + "x" + "^3 " + b + "x^2 " + c + "x " + d + " :");
double minusBover3a = -(b / (3 * a));
double rootp2 = (b * c / (6 * Math.Pow(a, 2))) - (Math.Pow(b, 3) / (27 * Math.Pow(a, 3))) - (d / (2 * a));
double rootp3 = (c / (3 * a)) - (Math.Pow(b, 2) / (9 * Math.Pow(a, 2)));
double bigCubeRootPlus = Math.Cbrt(rootp2 + Math.Sqrt(Math.Pow(rootp2, 2) + Math.Pow(rootp3, 3)));
double bigCubeRootMinus = Math.Cbrt(rootp2 - Math.Sqrt(Math.Pow(rootp2, 2) + Math.Pow(rootp3, 3)));
// ** THIS IS THE PROBLEM. "-1/2" uses integer division, so this complex has 0 for real part
Complex complexPlus = new Complex(-1.0 / 2, Math.Sqrt(3) / 2);
Complex complexMinus = new Complex(-1.0 / 2, -(Math.Sqrt(3) / 2));
Complex root1 = minusBover3a + bigCubeRootPlus + bigCubeRootMinus;
Complex root2 = minusBover3a + complexPlus * bigCubeRootPlus + complexMinus * bigCubeRootMinus;
Complex root3 = minusBover3a + complexMinus * bigCubeRootPlus + complexPlus * bigCubeRootMinus;

I admit I haven't tried your code, but you may have a casting issue in the math in your original calculations. Try this:
double rootp2 = ((double)b * (double)c / (6D * Math.Pow(a, 2D))) - (Math.Pow(b, 3D) / (27D * Math.Pow(a, 3D))) - ((double)d / (2D * (double)a));
If that makes a difference, you'd have to propagate a similar change (cast all variables as (double) and inline constants as double with D) through the other calculations.

The following is an alternative to your code:
// from https://www.daniweb.com/programming/software-development/
// code/454493/solving-the-cubic-equation-using-the-complex-struct
// algorithm described in
// https://en.wikipedia.org/wiki/Cubic_equation#General_cubic_formula
const int NRoots = 3;
double SquareRootof3 = Math.Sqrt(3);
// the 3 cubic roots of 1
var CubicUnity = new List<Complex>(NRoots)
{ new Complex(1, 0),
new Complex(-0.5, -SquareRootof3 / 2.0),
new Complex(-0.5, SquareRootof3 / 2.0) };
// intermediate calculations
double DELTA = 18 * a * b * c * d
- 4 * b * b * b * d
+ b * b * c * c
- 4 * a * c * c * c
- 27 * a * a * d * d;
double DELTA0 = b * b - 3 * a * c;
double DELTA1 = 2 * b * b * b
- 9 * a * b * c
+ 27 * a * a * d;
Complex DELTA2 = -27 * a * a * DELTA;
Complex C = Complex.Pow((DELTA1 + Complex.Pow(DELTA2, 0.5)) / 2, 1 / 3.0);
for (int i = 0; i < NRoots; i++)
{
Complex M = CubicUnity[i] * C;
Complex Root = -1.0 / (3 * a) * (b + M + DELTA0 / M);
Console.WriteLine();
Console.WriteLine($"Root {i+1}:");
Console.WriteLine($"Real {Root.Real:0.#####}");
Console.WriteLine($"Imaginary {Root.Imaginary:0.#####}i");
}

Related

Problem with calculating cubic equations in C#

Recently I was working on a discord bot to compute the roots of a cubic equation.
I have already made another program beforehand in C# that basically does the same thing, and is proven to work correctly, so I straight up copied the codes into the one which I am working with now.
(Suppose that I am calculating the roots of 7x3 + 2x2 + 12x + 9 = 0)
The code below is from the program which was created beforehand:
(Once again, the program and the results are proven to be correct, results are listed at the bottom of the code)*
// parts 1-5
double p1 = -(b / (3 * a));
double p2 = (b * c / (6 * Math.Pow(a, 2))) - (Math.Pow(b, 3) / (27 * Math.Pow(a, 3))) - (d / (2 * a));
double p3 = (c / (3 * a)) - (Math.Pow(b, 2) / (9 * Math.Pow(a, 2)));
Complex p4 = new Complex(-1.0 / 2, Math.Sqrt(3) / 2);
Complex p5 = new Complex(-1.0 / 2, -(Math.Sqrt(3) / 2));
// solve for roots
Complex root1 = p1 + Math.Cbrt(p2 + Math.Sqrt(Math.Pow(p2, 2) + Math.Pow(p3, 3))) +
Math.Cbrt(p2 - Math.Sqrt(Math.Pow(p2, 2) + Math.Pow(p3, 3)));
Complex root2 = p1 + (p4 * Math.Cbrt(p2 + Math.Sqrt(Math.Pow(p2, 2) + Math.Pow(p3, 3)))) +
(p5 * Math.Cbrt(p2 - Math.Sqrt(Math.Pow(p2, 2) + Math.Pow(p3, 3))));
Complex root3 = p1 + (p5 * Math.Cbrt(p2 + Math.Sqrt(Math.Pow(p2, 2) + Math.Pow(p3, 3)))) +
(p4 * Math.Cbrt(p2 - Math.Sqrt(Math.Pow(p2, 2) + Math.Pow(p3, 3))));
/*
results :
root1 = (-0.6566823203779361, 0)
root2 = (0.18548401733182518, 1.3868992549529795)
root3 = (0.18548401733182518, -1.3868992549529795)
*/
I proceed to copy the whole thing into the new program I am working on. Then I realized in my new program the Math.Cbrt function doesn't exist (I don't know why). Therefore I made a custom program to tackle this problem, here is the code in my new program :
(This is the problematic program, the results are different from the first one's.)
// parts 1-5
double p1 = -(b / (3 * a));
double p2 = (b * c / (6 * Math.Pow(a, 2))) - (Math.Pow(b, 3) / (27 * Math.Pow(a, 3))) - (d / (2 * a));
double p3 = (c / (3 * a)) - (Math.Pow(b, 2) / (9 * Math.Pow(a, 2)));
Complex p4 = new Complex(-1.0 / 2, Math.Sqrt(3.0) / 2);
Complex p5 = new Complex(-1.0 / 2, -(Math.Sqrt(3.0) / 2));
// solve for roots
Complex root1 = p1 + Cbrt(p2 + Math.Sqrt(Math.Pow(p2, 2) + Math.Pow(p3, 3))) +
Cbrt(p2 - Math.Sqrt(Math.Pow(p2, 2) + Math.Pow(p3, 3)));
Complex root2 = p1 + (p4 * Cbrt(p2 + Math.Sqrt(Math.Pow(p2, 2) + Math.Pow(p3, 3)))) +
(p5 * Cbrt(p2 - Math.Sqrt(Math.Pow(p2, 2) + Math.Pow(p3, 3))));
Complex root3 = p1 + (p5 * Cbrt(p2 + Math.Sqrt(Math.Pow(p2, 2) + Math.Pow(p3, 3)))) +
(p4 * Cbrt(p2 - Math.Sqrt(Math.Pow(p2, 2) + Math.Pow(p3, 3))));
public static Complex Cbrt(Complex value)
{
Complex result = Complex.Pow(value, 1D / 3);
return result;
}
/*
results :
root1 = (0.965490835755936, 0.936562108366076)
root2 = (0.185484017331825, -0.486224961779172)
root3 = (-1.43668913880205, -0.450337146586904)
*/
I have tried to extract different sections of the codes and run it separately but I still wasn't able to find what the cause is. If the codes are the same, why do they yield different results? Or is the Cbrt method I have created the real problem behind this?
Refering #mikuszefski 's comment,
The real cause behind this is that the Cbrt() function I have created calculates negative numbers wrongly.
For example, Cbrt(-1) should yield the result -1.
However, the answer I have gotten instead is (NaN, 0).
I have found the solution in another thread.

Iterative Expansion of an Equation

I'm trying to write a method that will perform an iterative expansion of an equation that, after the second iteration, has a defined pattern. I need to get the results for each iteration into a List<T>, so I need to stop at each.
The first few steps look like this:
Fraction step1 = whole + half;
Console.WriteLine(" 1: " + step1);
Fraction step2 = whole + whole / (whole * 2 + half);
Console.WriteLine(" 2: " + step2);
Fraction step3 = whole + whole / (whole * 2 + whole / (whole * 2 + half));
Console.WriteLine(" 3: " + step3);
Fraction step4 = whole + whole / (whole * 2 + whole / (whole * 2 + whole / (whole * 2 + half)));
Console.WriteLine(" 4: " + step4);
Fraction step5 = whole + whole / (whole * 2 + whole / (whole * 2 + whole / (whole * 2 + whole / (whole * 2 + half))));
Console.WriteLine(" 5: " + step5);
Basically after each iteration step >= 2, half gets replaced with whole / (whole * 2 + half) continuing on for n-iterations.
I'm not entirely sure how to write an iterative equation like that in C#, though.
Clarifications: There will be at least 1000 iterations. Only step 1 doesn't follow the pattern (I guess technically step 2 doesn't as it establishes the pattern).
Try this -
List<Fraction> steps = new List<Fraction>();
for (int i = 0; i < 5; i++)
{
if (i > 0)
half = whole / (whole * 2 + half);
var step = whole + half;
steps.Add(step);
Console.WriteLine($" {i + 1}: {step}");
}
All the steps are stored in steps list.

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 :)

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.

What does the '%' operator mean?

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.

Categories