generating completely random even numbers with C# - c#

is there any good method to generate random even numbers with C#? I came up with this code:
Random RandString = new Random(0);
code:
private void button6_Click(object sender, EventArgs e)
{
int min = 0;
int max = 50;
int rand = RandString.Next(min, max-1);
while (rand % 2 == 1) // odd
{
rand = RandString.Next(min, max-1);
}
textBox4.Text = "" + rand;
}
Problems with this code:
my current solution might not be the fastest of all
very often, numbers that are generated by this method are repeated with the same sequence! For example after 5 iterations I can get: 8, 10, 20, 30, 16. After more clicking (for like 15 seconds) I can get 10, 30, 20 in a row or 30, 20, 10.. I'm not sure, but that's NOT what I call "random".
so is there any way to deal with the problem that I've described, or is there any other method?

textBox4.Text = (2 * rand.Next(min / 2, max / 2)).ToString();

even easier would be to take your result and multiply it by 2
private void button6_Click(object sender, EventArgs e)
{
int min = 0;
int max = 25;
int rand = RandString.Next(min, max-1)*2;
textBox4.Text = rand.ToString();
}

Random random = new Random();
int nextnum = random.Next(min/2,max/2) * 2

You could use the RNGCryptoServiceProvider to get a "more random" (which is a silly term I admit) number. There is a nice eample on MSDN's documentation page.
As others recommended, you can just multiply the result with 2 to get an even number.

There are a number of flaws in your approach.
First of all, Random from .NET isn't completely random in the cryptographic sense AFAIK, but it should be much much better than the results you report. Most likely, you are creating a new Random object on every iteration of your loop; since the current system time is used to seed the RNG, you will get the same sequences of pseudo-random numbers if you do runs very short after one another. Instead, create one instance of Random at startup, and keep it around for as long as possible.
Then, creating an even number from a random integer is much easier than looping until you find one that happens to be even: just generate one random number and clear the least significant bit: myRand.Next(min, max-1) & ~1;. A decent RNG has a uniform distribution over all of its bits, so clearing any bit shouldn't reduce entropy by more than, well, one bit.
Getting back to the 'completely random' part: Random provides a pseudo-random number generator. It is seeded once, based on a value that is somewhat random-ish (the least-significant parts of the current system time), but given the same seed, the RNG will reliably and deterministically produce the same numbers on every run. If you want true randomness (a.k.a. 'entropy'), you'd be surprised how hard it is to produce it on a machine that was built for deterministic calculations. UNIX and Unix-like systems typically offer a pool of entropy through a special kernel-generated file (/dev/random), using things like hard disk access timing, network noise, and whatever other sources of actual randomness they can find, and distillate those into a uniform distribution using fairly complicated calculations. Windows can probably do the same, but I am unaware of any API for this in either .NET or the classic win32 API.

Related

Does increasing RNG seed by 1 each time ensure not getting same consecutive values?

I've had a chance to see some interesting piece of code that was either used as an April Fools joke (update became public on April 1st) or was just a bug, because someone did not understand how to use RNGs.
Question is related to Random class being part of .NET/C#, but maybe other RNGs work the same way.
Simplified version of the code I found, after taking out all the unnecessary details, would look like this:
for ( int i = startI; i < stopI; ++i ) {
int newValue = new Random( i ).Next( 0, 3 ); // new RNG with seed i generates a single value from 3 options: 0, 1 and 2
// rest of code
}
I did run simple test of that code in LINQPad to see if what I was observing in program was just my "luck" or whether maybe that's actually how RNG used this way will work. Here's the code:
int lastChoice = -1;
int streakLength = -1;
for ( int i = 0; i < 100000000; ++i ) {
int newChoice = new Random( i ).Next( 0, 3 );
if ( newChoice == lastChoice ) {
streakLength++;
( i + ";" + lastChoice + ";" + streakLength ).Dump();
} else {
lastChoice = newChoice;
streakLength = 1;
}
}
"The End".Dump();
(The Dump() method simply prints the value to the screen)
The result of running this "script" was just "The End", nothing more. It means, that for 100M cycles of generating a random value, not a single time was it able to generate same consecutive values, when having only 3 of them as an option.
So back to my question from the title - does increasing the seed of RNG (specifically the .NET/C#'s Random class, but general answer is also welcome) by one after every (integer) random number generation would ensure that no repeated consecutive values would occur? Or is that just pure luck?
The behavior you show depends on the PRNG.
For many PRNGs, including linear PRNGs such as the one implemented in the .NET Framework's System.Random, if you initialize two instances of a PRNG with consecutive seeds, the number sequences they produce may be correlated with each other, even though each of those sequences produces random-behaving numbers on its own. The behavior you describe in your question is just one possible result of this.
For System.Random in particular, this phenomenon is described in further detail in "A Primer on Repeatable Random Numbers".
Other PRNGs, however, give each seed its own independent pseudorandom number sequence (an example is SFC64 and counter-based PRNGs; see, e.g., "Parallel Random Numbers: As Easy as 1, 2, 3"), and some PRNGs can be "jumped ahead" a huge number of steps to produce pseudorandom number sequences that are independent with respect to each other.
See also:
Impact of setting random.seed() to recreate a simulated behaviour and choosing the seed
Seeding Multiple Random Number Generators

How to do a number of random trials efficiently?

Let say an event have the probability P to succeed. (0 < P < 1 )
and I have to make N tests to see if this happens and I want the total number of successes:
I could go
int countSuccesses = 0;
while(N-- > 0)
{
if(Random.NextDouble()<P) countSuccesses++; // NextDouble is from 0.0 to 1.0
}
But is there not a more efficient way to do this? I want to have a single formula so I just can use ONE draw random number to determine the total number of successes. (EDIT The idea of using only one draw was to get below O(n))
I want to be able call a method
GetSuccesses( n, P)
and it to be O(1)
UPDATE
I will try to go with the
MathNet.Numerics.Distributions.Binomial.Sample(P, n)
even if it might be using more then only one random number I'll guess it will be faster than O(n) even if its not O(1). I'll benchmark that. Big thanks to David and Rici.
UPDATE
The binomial sample above was O(n) so it did not help me. But thanks to a comment done by Fred I just switched to
MathNet.Numerics.Distributions.Normal.Sample(mean, stddev)
where
mean = n * P
stddev = Math.Sqrt(n * P * (1 - P));
and now it is O(1) !
Per #rici for small N you can use the CDF or PMF of the Binomial Distribution, and simply compare the random input with the probabibilities for 0,1,2..N successes.
Something like:
static void Main(string[] args)
{
var trials = 10;
var trialProbability = 0.25;
for (double p = 0; p <= 1; p += 0.01)
{
var i = GetSuccesses(trials, trialProbability, p);
Console.WriteLine($"{i} Successes out of {trials} with P={trialProbability} at {p}");
}
Console.ReadKey();
}
static int GetSuccesses(int N, double P, double rand)
{
for (int i = 0; i <= N; i++)
{
var p_of_i_successes = MathNet.Numerics.Distributions.Binomial.PMF(P, N, i);
if (p_of_i_successes >= rand)
return i;
rand -= p_of_i_successes;
}
return N;
}
I'm not going to write formula here, as it's already in wiki, and I don't really know good formatting here for such things.
Probability for each outcome can be determined by Bernulli formula
https://en.wikipedia.org/wiki/Bernoulli_trial
What you need to do is to calculate binominal coefficient, then probability calculation becomes quite easy - multiply binominal coefficient by p and q in appropriate powers. Fill in array P[0..n] that contains probability for each outcome - number of exactly i successes.
After set up go from 0 up to n and calculate rolling sum of probabilities.
Check lower/upper bounds against random value and once it's inside current interval, return the outcome.
So, deciding part will be like this:
sum=0;
for (int i = 0; i <= n; i++)
if (sum-eps < R && sum+P[i]+eps > R)
return i;
else
sum+=P[i];
Here eps is small floating point value to overcome floating point rounding issues, R is saved random value, P is an array of probabilities I mentioned before.
Unfortunately, this method is not practical for big N (20 or 100+):
you'll get quite big impact of rounding errors
random numbers generator can be not determinitive enough to cover every possible outcome with proper probabilities distribution
Based on how you've phrased the question, this is impossible to do.
Your are essentially asking how to ensure that a single coin flip (i.e. one randomized outcome) is exactly 50% heads and 50% tails, which is impossible.
Even if you were to use two random numbers, where you expect one heads and one tails; this test would fail in 50% of all cases (because you might get two heads or two tails).
Probablility is founded on the law of large numbers. This explicitly states that a small sampling cannot be expected to accurately reflect the expected outcome.
The LLN is important because it guarantees stable long-term results for the averages of some random events. For example, while a casino may lose money in a single spin of the roulette wheel, its earnings will tend towards a predictable percentage over a large number of spins. Any winning streak by a player will eventually be overcome by the parameters of the game. It is important to remember that the law only applies (as the name indicates) when a large number of observations is considered. There is no principle that a small number of observations will coincide with the expected value or that a streak of one value will immediately be "balanced" by the others (see the gambler's fallacy).
When I asked this as a comment; you replied:
#Flater No, I am making N actual draws but with only one random number.
But this doesn't make sense. If you only use one random value, and keep using that same value, then every draw is obviously going to give you the exact same outcome (that same number).
The closest I can interpret your question in a way that is not impossible would be that you were mistakenly referring to a single random seed as a single random number.
A random seed (or seed state, or just seed) is a number (or vector) used to initialize a pseudorandom number generator.
For a seed to be used in a pseudorandom number generator, it does not need to be random. Because of the nature of number generating algorithms, so long as the original seed is ignored, the rest of the values that the algorithm generates will follow probability distribution in a pseudorandom manner.
However, your explicitly mentioned expectations seem to disprove that assumption. You want to do something like:
GetSuccesses( n, P, Random.NextDouble())
and you're also expecting to get a O(1) operation, which flies in the face of the law of large numbers.
If you're actually talking about having a single random seed; then your expectation are not correct.
If you make N draws, the operation is still of O(N) complexity. Whether you randomize the seed after every draw or not is irrelevant, it's always O(N).
GetSuccesses( n, P, Random.NextDouble()) is going to give you one draw, not one seed. Regardless of terminology used, your expectation of the code is not related to using the same seed for several draws.
As the question is currently phrased; what you want is impossible. Repeated comments for clarification by several commenter have not yet yielded a clearer picture.
As a sidenote, I find it very weird that you've answered to every comment except when directly asked if you are talking about a seed instead of a number (twice now).
#David and #rici pointed me to the
MathNet.Numerics.Distributions.Binomial.Sample(P, n)
A benchmark told me that it also O(n) and in par with my original
int countSuccesses = 0;
while(N-- > 0)
{
if(Random.NextDouble()<P) countSuccesses++; // NextDouble is from 0.0 to 1.0
}
But thanks to a comment done by Fred:
You could turn that random number into a gaussian sample with mean N*P, which would have the same distribution as your initial function
I just switched to
MathNet.Numerics.Distributions.Normal.Sample(mean, stddev)
where
mean = n * P
stddev = Math.Sqrt(n * P * (1 - P));
and now it is O(1) !
and the function I wanted got to be:
private int GetSuccesses(double p, int n)
{
double mean = n * p;
double stddev = Math.Sqrt(n * p * (1 - p));
double hits = MathNet.Numerics.Distributions.Normal.Sample(Random, mean, stddev);
return (int)Math.Round(hits, 0);
}
As Paul pointed out,
this is an approximation, but one that I gladly accept.

3 digit random number in C#

Is there a better way to generate 3 digit random number than the following:
var now = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture);
string my3digitrandomnumber = now.Substring(now.Length - 7, 3);
Thanks..
Yes - your current code isn't random at all. It's based on the system time. In particular, if you use this from several threads at the same time - or even several times within the same thread in quick succession - you'll get the same number each time.
You should be using Random or RandomNumberGenerator (which is more secure).
For example, once you've got an instance of Random, you could use:
int value = rng.Next(1000);
string text = value.ToString("000");
(That's assuming you want the digits as text. If you want an integer which is guaranteed to be three digits, use rng.Next(100, 1000).)
However, there are caveats around Random:
You don't want to create a new instance each time you use it; that would also be time based unless you specify a seed
It's not thread-safe
So ideally you probably want one per thread. My article on randomness talks more about this and gives some sample code.
int r = (new Random()).Next(100, 1000);
You can use the Random class and call Next(10) three times.
Well, firstly that's an odd setup you have there, why do you first get the date?
You should use this to get a number of 3 digits (less than 1000).
Random rand = new Random(); // <-- Make this static somewhere
const int maxValue = 999;
string number = rand.Next(maxValue + 1).ToString("D3");
The maxValue + 1 is because the paramter for Random.Next(int) is an exclusive upper bound, meaning that the number returned will always be less than the parameter. It can never be equal to it.
new Random.NextDouble() * 1000

Random.Next() - finding the Nth .Next()

Given a consistently seeded Random:
Random r = new Random(0);
Calling r.Next() consistently produces the same series; so is there a way to quickly discover the N-th value in that series, without calling r.Next() N times?
My scenario is a huge array of values created via r.Next(). The app occasionally reads a value from the array at arbitrary indexes. I'd like to optimize memory usage by eliminating the array and instead, generating the values on demand. But brute-forcing r.Next() 5 million times to simulate the 5 millionth index of the array is more expensive than storing the array. Is it possible to short-cut your way to the Nth .Next() value, without / with less looping?
I don't know the details of the PRNG used in the BCL, but my guess is that you will find it extremely difficult / impossible to find a nice, closed-form solution for N-th value of the series.
How about this workaround:
Make the seed to the random-number generator the desired index, and then pick the first generated number. This is equally 'deterministic', and gives you a wide range to play with in O(1) space.
static int GetRandomNumber(int index)
{
return new Random(index).Next();
}
In theory if you knew the exact algorithm and the initial state you'd be able to duplicate the series but the end result would just be identical to calling r.next().
Depending on how 'good' you need your random numbers to be you might consider creating your own PRNG based on a Linear congruential generator which is relatively easy/fast to generate numbers for. If you can live with a "bad" PRNG there are likely other algorithms that may be better to use for your purpose. Whether this would be faster/better than just storing a large array of numbers from r.next() is another question.
No, I don't believe there is. For some RNG algorithms (such as linear congruential generators) it's possible in principle to get the n'th value without iterating through n steps, but the Random class doesn't provide a way of doing that.
I'm not sure whether the algorithm it uses makes it possible in principle -- it's a variant (details not disclosed in documentation) of Knuth's subtractive RNG, and it seems like the original Knuth RNG should be equivalent to some sort of polynomial-arithmetic thing that would allow access to the n'th value, but (1) I haven't actually checked that and (2) whatever tweaks Microsoft have made might break that.
If you have a good enough "scrambling" function f then you can use f(0), f(1), f(2), ... as your sequence of random numbers, instead of f(0), f(f(0)), f(f(f(0))), etc. (the latter being roughly what most RNGs do) and then of course it's trivial to start the sequence at any point you please. But you'll need to choose a good f, and it'll probably be slower than a standard RNG.
You could build your own on-demand dictionary of 'indexes' & 'random values'. This assumes that you will always 'demand' indexes in the same order each time the program runs or that you don't care if the results are the same each time the program runs.
Random rnd = new Random(0);
Dictionary<int,int> randomNumbers = new Dictionary<int,int>();
int getRandomNumber(int index)
{
if (!randomNumbers.ContainsKey(index))
randomNumbers[index] = rnd.Next();
return randomNumbers[index];
}

How do I find the average in a LARGE set of numbers?

I have a large set of numbers, probably in the multiple gigabytes range. First issue is that I can't store all of these in memory. Second is that any attempt at addition of these will result in an overflow. I was thinking of using more of a rolling average, but it needs to be accurate. Any ideas?
These are all floating point numbers.
This is not read from a database, it is a CSV file collected from multiple sources. It has to be accurate as it is stored as parts of a second (e.g; 0.293482888929) and a rolling average can be the difference between .2 and .3
It is a set of #'s representing how long users took to respond to certain form actions. For example when showing a messagebox, how long did it take them to press OK or Cancel. The data was sent to me stored as seconds.portions of a second; 1.2347 seconds for example. Converting it to milliseconds and I overflow int, long, etc.. rather quickly. Even if I don't convert it, I still overflow it rather quickly. I guess the one answer below is correct, that maybe I don't have to be 100% accurate, just look within a certain range inside of a sepcific StdDev and I would be close enough.
You can sample randomly from your set ("population") to get an average ("mean"). The accuracy will be determined by how much your samples vary (as determined by "standard deviation" or variance).
The advantage is that you have billions of observations, and you only have to sample a fraction of them to get a decent accuracy or the "confidence range" of your choice. If the conditions are right, this cuts down the amount of work you will be doing.
Here's a numerical library for C# that includes a random sequence generator. Just make a random sequence of numbers that reference indices in your array of elements (from 1 to x, the number of elements in your array). Dereference to get the values, and then calculate your mean and standard deviation.
If you want to test the distribution of your data, consider using the Chi-Squared Fit test or the K-S test, which you'll find in many spreadsheet and statistical packages (e.g., R). That will help confirm whether this approach is usable or not.
Integers or floats?
If they're integers, you need to accumulate a frequency distribution by reading the numbers and recording how many of each value you see. That can be averaged easily.
For floating point, this is a bit of a problem. Given the overall range of the floats, and the actual distribution, you have to work out a bin-size that preserves the accuracy you want without preserving all of the numbers.
Edit
First, you need to sample your data to get a mean and a standard deviation. A few thousand points should be good enough.
Then, you need to determine a respectable range. Folks pick things like ±6σ (standard deviations) around the mean. You'll divide this range into as many buckets as you can stand.
In effect, the number of buckets determines the number of significant digits in your average. So, pick 10,000 or 100,000 buckets to get 4 or 5 digits of precision. Since it's a measurement, odds are good that your measurements only have two or three digits.
Edit
What you'll discover is that the mean of your initial sample is very close to the mean of any other sample. And any sample mean is close to the population mean. You'll note that most (but not all) of your means are with 1 standard deviation of each other.
You should find that your measurement errors and inaccuracies are larger than your standard deviation.
This means that a sample mean is as useful as a population mean.
Wouldn't a rolling average be as accurate as anything else (discounting rounding errors, I mean)? It might be kind of slow because of all the dividing.
You could group batches of numbers and average them recursively. Like average 100 numbers 100 times, then average the result. This would be less thrashing and mostly addition.
In fact, if you added 256 or 512 at once you might be able to bit-shift the result by either 8 or 9, (I believe you could do this in a double by simply changing the floating point mantissa)--this would make your program extremely quick and it could be written recursively in just a few lines of code (not counting the unsafe operation of the mantissa shift).
Perhaps dividing by 256 would already use this optimization? I may have to speed test dividing by 255 vs 256 and see if there is some massive improvement. I'm guessing not.
You mean of 32-bit and 64-bit numbers. But why not just use a proper Rational Big Num library? If you have so much data and you want an exact mean, then just code it.
class RationalBignum {
public Bignum Numerator { get; set; }
public Bignum Denominator { get; set; }
}
class BigMeanr {
public static int Main(string[] argv) {
var sum = new RationalBignum(0);
var n = new Bignum(0);
using (var s = new FileStream(argv[0])) {
using (var r = new BinaryReader(s)) {
try {
while (true) {
var flt = r.ReadSingle();
rat = new RationalBignum(flt);
sum += rat;
n++;
}
}
catch (EndOfStreamException) {
break;
}
}
}
Console.WriteLine("The mean is: {0}", sum / n);
}
}
Just remember, there are more numeric types out there than the ones your compiler offers you.
You could break the data into sets of, say, 1000 numbers, average these, and then average the averages.
This is a classic divide-and-conquer type problem.
The issue is that the average of a large set of numbers is the same
as the average of the first-half of the set, averaged with the average of the second-half of the set.
In other words:
AVG(A[1..N]) == AVG( AVG(A[1..N/2]), AVG(A[N/2..N]) )
Here is a simple, C#, recursive solution.
Its passed my tests, and should be completely correct.
public struct SubAverage
{
public float Average;
public int Count;
};
static SubAverage AverageMegaList(List<float> aList)
{
if (aList.Count <= 500) // Brute-force average 500 numbers or less.
{
SubAverage avg;
avg.Average = 0;
avg.Count = aList.Count;
foreach(float f in aList)
{
avg.Average += f;
}
avg.Average /= avg.Count;
return avg;
}
// For more than 500 numbers, break the list into two sub-lists.
SubAverage subAvg_A = AverageMegaList(aList.GetRange(0, aList.Count/2));
SubAverage subAvg_B = AverageMegaList(aList.GetRange(aList.Count/2, aList.Count-aList.Count/2));
SubAverage finalAnswer;
finalAnswer.Average = subAvg_A.Average * subAvg_A.Count/aList.Count +
subAvg_B.Average * subAvg_B.Count/aList.Count;
finalAnswer.Count = aList.Count;
Console.WriteLine("The average of {0} numbers is {1}",
finalAnswer.Count, finalAnswer.Average);
return finalAnswer;
}
The trick is that you're worried about an overflow. In that case, it all comes down to order of execution. The basic formula is like this:
Given:
A = current avg
C = count of items
V = next value in the sequence
The next average (A1) is:
(C * A) + V
A1 = ———————————
C + 1
The danger is over the course of evaulating the sequence, while A should stay relatively manageable C will become very large.
Eventually C * A will overflow the integer or double types.
One thing we can try is to re-write it like this, to reduce the chance of an overflow:
A1 = C/(C+1) * A/(C+1) + V/(C+1)
In this way, we never multiply C * A and only deal with smaller numbers. But the concern now is the result of the division operations. If C is very large, C/C+1 (for example) may not be meaningful when constrained to normal floating point representations. The best I can suggest is to use the largest type possible for C here.
Here's one way to do it in pseudocode:
average=first
count=1
while more:
count+=1
diff=next-average
average+=diff/count
return average
Sorry for the late comment, but isn't it the formula above provided by Joel Coehoorn rewritten wrongly?
I mean, the basic formula is right:
Given:
A = current avg
C = count of items
V = next value in the sequence
The next average (A1) is:
A1 = ( (C * A) + V ) / ( C + 1 )
But instead of:
A1 = C/(C+1) * A/(C+1) + V/(C+1)
shouldn't we have:
A1 = C/(C+1) * A + V/(C+1)
That would explain kastermester's post:
"My math ticks off here - You have C, which you say "go towards infinity" or at least, a really big number, then: C/(C+1) goes towards 1. A /(C+1) goes towards 0. V/(C+1) goes towards 0. All in all: A1 = 1 * 0 + 0 So put shortly A1 goes towards 0 - seems a bit off. – kastermester"
Because we would have A1 = 1 * A + 0, i.e., A1 goes towards A, which it's right.
I've been using such method for calculating averages for a long time and the aforementioned precision problems have never been an issue for me.
With floating point numbers the problem is not overflow, but loss of precision when the accumulated value gets large. Adding a small number to a huge accumulated value will result in losing most of the bits of the small number.
There is a clever solution by the author of the IEEE floating point standard himself, the Kahan summation algorithm, which deals exactly with this kind of problems by checking the error at each step and keeping a running compensation term that prevents losing the small values.
If the numbers are int's, accumulate the total in a long. If the numbers are long's ... what language are you using? In Java you could accumulate the total in a BigInteger, which is an integer which will grow as large as it needs to be. You could always write your own class to reproduce this functionality. The gist of it is just to make an array of integers to hold each "big number". When you add two numbers, loop through starting with the low-order value. If the result of the addition sets the high order bit, clear this bit and carry the one to the next column.
Another option would be to find the average of, say, 1000 numbers at a time. Hold these intermediate results, then when you're done average them all together.
Why is a sum of floating point numbers overflowing? In order for that to happen, you would need to have values near the max float value, which sounds odd.
If you were dealing with integers I'd suggest using a BigInteger, or breaking the set into multiple subsets, recursively averaging the subsets, then averaging the averages.
If you're dealing with floats, it gets a bit weird. A rolling average could become very inaccurate. I suggest using a rolling average which is only updated when you hit an overflow exception or the end of the set. So effectively dividing the set into non-overflowing sets.
Two ideas from me:
If the numbers are ints, use an arbitrary precision library like IntX - this could be too slow, though
If the numbers are floats and you know the total amount, you can divide each entry by that number and add up the result. If you use double, the precision should be sufficient.
Why not just scale the numbers (down) before computing the average?
If I were to find the mean of billions of doubles as accurately as possible, I would take the following approach (NOT TESTED):
Find out 'M', an upper bound for log2(nb_of_input_data). If there are billions of data, 50 may be a good candidate (> 1 000 000 billions capacity). Create an L1 array of M double elements. If you're not sure about M, creating an extensible list will solve the issue, but it is slower.
Also create an associated L2 boolean array (all cells set to false by default).
For each incoming data D:
int i = 0;
double localMean = D;
while (L2[i]) {
L2[i] = false;
localMean = (localMean + L1[i]) / 2;
i++;
}
L1[i] = localMean;
L2[i] = true;
And your final mean will be:
double sum = 0;
double totalWeight = 0;
for (int i = 0; i < 50) {
if (L2[i]) {
long weight = 1 << i;
sum += L1[i] * weight;
totalWeight += weight;
}
}
return sum / totalWeight;
Notes:
Many proposed solutions in this thread miss the point of lost precision.
Using binary instead of 100-group-or-whatever provides better precision, and doubles can be safely doubled or halved without losing precision!
Try this
Iterate through the numbers incrementing a counter, and adding each number to a total, until adding the next number would result in an overflow, or you run out of numbers.
( It makes no difference if the inputs are integers or floats - use the largest precision float you can and convert each input to that type)
Divide the total by the counter to get a mean ( a floating point), and add it to a temp array
If you had run out of numbers, and there is only one element in temp, that's your result.
Start over using the temp array as input, ie iteratively recurse until you reached the end condition described earlier.
depending on the range of numbers it might be a good idea to have an array where the subscript is your number and the value is the quantity of that number, you could then do your calculation from this

Categories

Resources