Related
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");
}
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 is the order of growth of the following function?
static int counter = 0;
static void Example(int n)
{
if (n == 1) return;
for (int i = 0; i < n; i++)
{
counter++;
}
Example(n / 2);
}
In order to solve it I have done the following:
I first got rid of the inner for loop in order to end up with:
static void Example(int n)
{
if (n == 1) return;
counter++;
Example(n / 2);
}
By analyzing that I was able to tell that the order of growth of that method was log base 2 of n .
so I am thinking that the final answer will be log base 2 times something else. How can I figure it out?
Let's look at both the original and the modified function. In the original function, you have the following amount of work done:
A constant amount of work for the base case check.
O(n) work to count up the number.
The work required for a recursive call to something half the size.
We can express this as a recurrence relation:
T(1) = 1
T(n) = n + T(n / 2)
Let's see what this looks like. We can start expanding this out by noting that
T(n) = n + T(n / 2)
= n + (n / 2 + T(n / 4)
= n + n/2 + T(n / 4)
= n + n/2 + (n / 4 + T(n / 8))
= n + n/2 + n/4 + T(n / 8)
We can start to see a pattern here. If we expand out the T(n / 2) bit k times, we get
T(n) = n + n/2 + n/4 + ... + n/2k + T(n/2k)
Eventually, this stops when n / 2k = 1. When this happens, we have
T(n) = n + n/2 + n/4 + n/8 + ... + 1
What does this evaluate to? Interestingly, this sum is equal to 2n + 1, because the sum n + n/2 + n/4 + n/8 + ... = 2n. Consequently, this first function is O(n). We could have also arrived at this conclusion by using the Master Theorem, but it's interesting to see this approach as well.
So now let's look at the new function. This one does
A constant amount of work for the base case check.
The work required for a recursive call to something half the size.
We can write this recurrence as
T(1) = 1
T(n) = 1 + T(n / 2)
Using the same trick as before, let's expand out T(n):
T(n) = 1 + T(n / 2)
= 1 + 1 + T(n / 4)
= 1 + 1 + 1 + T(n / 8)
More generally, after expanding out k times, we get
T(n) = k + T(n / 2k)
This stops when n / 2k = 1, which happens when k = log2 n (that is, lg n). In this case, we get that
T(n) = lg n + T(1) = lg n + 1
So T(n) = O(lg n) in this case.
Hope this helps!
Let's see now.. this will add 1 to the counter n times.
each call n is reduced by half until it reaches one.
You can get rid of the loop and use
counter+=n;
instead, because basically the loop adds n to counter, 1 by one.
This means that n will be added to the counter each time it runs, and then become smaller by 2 until it reaches one.
so say n = 40.
counter:
40 -> 60 -> 70 -> 75 -> 77 -> 77.
n:
40 -> 20 -> 10 -> 5 -> 2 -> 1.
Just a push in the right direction (counter+=n; being the important part)
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.
I have to report average value of incoming numbers, how i could do that without using some sort of data structure to keep track of all values and then calculating average by summing them and dividing by number of values?
Just keep running sum and how many numbers you have received, that's all you need to compute the average.
If I'm not totally mistaken, one could calculate the avg(n+1) also this way:
avg(n+1) = (a[1]+ ... + a[n+1]) / (n+1) =
= (a[1]+ ... + a[n])/(n+1) + a[n+1]/(n+1) =
= (n(a[1]+ ... + a[n])/n) / (n+1) + a[n+1]/(n+1) =
= n*avg(n) / (n+1) + a[n+1]/(n+1) =
= n/(n+1) * avg(n) + a[n+1]/(n+1)
so multiply the old avg by n/(n+1) and add the new element divided by n+1. Depending on how high n will get and how big your values are, this could reduce rounding errors...
EDIT: Of course you have to calculate n/(n+1) using floats, otherwise it will always render 0...
If you have the numbers a[1] a[2] ... a[n] and you know their average is avg(n) = (a[1] + ... + a[n]) / n, then when you get another number a[n + 1] you can do:
avg(n + 1) = (avg(n) * n + a[n + 1]) / (n + 1)
Some floating point errors are unavoidable, but you should test this and see if it's good enough.
To avoid overflow, you could do the division first:
avg(n + 1) = (avg(n) / (n + 1)) * n + (a[n + 1] / (n + 1))
Keep the current sum and count. Update both on every incoming number.
avg = sum / count.
you don't need to keep track the total sum, only counter:
class Averager {
float currentAverage;
size_t count;
float addData (float value) {
this->currentAverage += (value - this->currentAverage) / ++count;
return this->currentAverage;
}
}
from-> prevent long running averaging from overflow?