 # A Series code in C#?

// Someone could explain, Why this code, do not output yet exactly the same List as the series component?

``````private void RunScript(double Start, double Step, int Count, ref object Series)
{
List<double> numbers = new List<double>();

// S = Start
// N = Step
// C = Count

for (double i = Start; i < Start + (Step * Count); i += Step){
}
Series = numbers;

}
``````

SeriesInC#.gh (9.1 KB)

You are missing the minus 1 in the condition of your for loop. It should be

private void RunScript(double Start, double Step, int Count, ref object Series)
{
List numbers = new List();

``````// S = Start
// N = Step
// C = Count

for (double i = Start; i < Start + (Step * Count) - 1; i += Step){
}
Series = numbers;
``````

}

I would recommend not using floating point maths to determine loop iterations. Whether or not your supposedly final `i` value is going to be `30.00000000002` or `29.9999999998` might as well be a matter of chance.

Use integers to count loop iterations and compute the floating point value afresh inside each iteration.

3 Likes

Dear Michael Pryor !

Best.

Andres

Dear DavidRutten,

I try this way, as a recursive Function, and is working now:
There is a simple way to do it?

Thanks
Best!
Andres

``````private void RunScript(double iStart, double iStep, int iCount, ref object A)
{
List<double> numbers = new List<double>();

iCount = iCount - 1;

A = mySeries(iStart, iCount, iStep, numbers);
}

List<double> mySeries (double start, int count, double step, List<double>numbers){

if (count > 0){
count = count - 1;
start = start + step;
// recursive function
mySeries(start, count, step, numbers);
}
return numbers;
}
``````

SeriesInC#-RecursiveFunction.gh (8.4 KB)

Yeah don’t use recursion if you can help it. C# is stack recursive, not tail-recursive so there’s only so many steps you can take before you get a stack overflow exception.

``````double[] numbers = new double[Count];
for (int i = 0; i < Count; i++)
numbers[i] = Start + i * Step;
``````
1 Like

Thanks David!
SeriesinC# Array + a for Loop!
I share the code here, for any one else who is learning as me! :SeriesinC#Array forLoop.gh (11.4 KB)

private void RunScript(double Start, double Step, int Count, ref object A)
{
double numbers = new double[Count];

``````for (int i = 0; i < Count; i++){
numbers[i] = Start + i * Step;
}

A = numbers;
``````

}

Quick tip, if you put triple backticks around multiline code it will format correctly on discourse.