You may want to
- Pre-allocate the array if you know it is going to contain exactly 100 elements, using
var xr_arr = new double[100]; Alternatively, if you don't know the exact number of items upfront, you can use a List<double> to add the new number to.
- Wait with trying to print the values until after you are done adding them.
So do it like:
static void xn()
{
double r = 3.9;
var n = 0;
// I think the number of elements could (theoretically) be different from 100
// and you could get an IndexOutOufRangeException if it is 101.
var increment = 0.01d; // 1.0d/300.0d; // <== try this.
var n_expected = 100; // 300 // <= with this.
var x_arr = new double[n_expected];
// alternative: if you cannot be absolutely certain about the number of elements.
//var x_list = new List<double>();
for (double x = 0; x <= 1; x += increment)
{
double xr = r * x * (1 - x);
x_arr[n++] = xr;
// x_list.Add(xr); // alternative.
}
for (int y = 0; y <23; y++)
{
Console.WriteLine(xr_arr[y]);
// Console.WriteLine(xr_list[y]); // alternative.
}
}
Floating point precision problems
Note that, unlike the general expectation, floating point values are still stored in a limited number of bits, and therefore subject to encoding resolution and rounding effects, make you loose precision if you perform operations such as addition, in a loop. It is a common mistake to expect that real numbers work the same on a computer as in pure math. Please have a look at what every computer scientist should know about floating point arithmetic, and the article it refers to.
In this example, if you had incremented by 1.0/300, expecting to get 300 elements, you would have had a problem.
xr_arrhave only 1 value..