Calculation Not Updating - c#

I have been running this syntax with one variable successfully, but now I am trying to change it to a foeach() loop and take a range of values and show the results as a message box. My issue with the syntax is that ecll always retains the value of the first number passed, and the calculation is never updated for each subsequent number in the array.
Where did I err that is preventing this from being updated for each subsequent number in the array?
private void btnGetData_Click(object sender, EventArgs e)
{
int start = 2;
int end = 10;
int[] nums = Enumerable.Range(start, end - start).ToArray();
foreach (int n in nums)
{
float tp_x = 0, tp_y = 0;
SAP = new List<PointF>();
float fbw = m_pd.bl[m_pd.bl.Count - 1].m_Width;
float Location1_X = tp_x + fbw;
float Location1_Y = tp_y;
SAP.Add(new PointF(Location1_X, Location1_Y));
float iBH = gbh(m_pd.bl.Count - 1);
float lbw = m_pd.bl[0].m_Width;
float Location2_X = tp_x + lbw;
float Location2_Y = tp_y + (iBH) + 1.5f;
PointF rip = new PointF();
if (!Getrip(ftp, rhep, ref rip))
{
SAP = null;
return;
}
for (int iRowIndex = saii; iRowIndex < m_pd.pp.Count; iRowIndex++)
{
float Xvalue = m_pd.pp[iRowIndex].X;
float Yvalue = m_pd.pp[iRowIndex].Y;
SAP.Add(new PointF(Xvalue, Yvalue));
if (Yvalue == LeftIntersectionPoint.Y)
{
pp.X = Xvalue;
pp.Y = Yvalue;
continue;
}
if (Xvalue >= rip.X)
{
Xvalue = rip.X;
SAP[SAP.Count - 1] = new PointF(rip.X, rip.Y);
}
if (Xvalue == rip.X)
{
break;
}
pp.X = Xvalue;
pp.Y = Yvalue;
}
double ecll = Getll(Location1_X, Location1_Y, rip.X, rip.Y);
Messagebox.Show(Convert.ToString(ec11));
txtLength.Text = ll.ToString("0.00");
}
}

I feel like this is more of a comment based on what's going on here, but I kind of need the code section to explain this better I believe.
Let's simplify away from your points, widths, etc. I think we can all agree that n is never used within your function, so let's do a similar example:
So I have a function I wrote that adds 1 to 1
var newNum = 1 + 1;
It does what is expected, sets newNum to 2, but let's say I wanted to enhance it so that it adds 1 to the numbers in nums (from your original function):
int start = 2;
int end = 10;
int[] nums = Enumerable.Range(start, end - start).ToArray();
but if I try to reuse my function outright:
foreach (int n in nums)
{
var newNum = 1 + 1;
}
Every single pass, I'm always going to have newNum set at 2 because I'm not using the variable.
what I should do is write this:
foreach (int n in nums)
{
var newNum = 1 + n;
}
so based on your 2 through 10, I should see newNum set to 3 through 11 at various iterations.

Each iteration in the 'Foreach' loop assigns a new value to 'n'.
However in the loop body, that value (n) is not used anywhere in the calculations (unless I am missing something). So, of course the result of these calculations will always be the same.
As soon as you include 'n' in some of the calclations, the result will change...

Related

How to split an array into intervals with given width and check count how many times, the values have appeared in each intervals C#?

In my array, arr3 has 1000 numbers in it. I have to split this array into k subintervals of width differenceofMaxMin . How can I do that? Later I have to count how many times, the values in arr3 have matched to each interval. But I am stuck at creating intervals from array with a given width.
Any kind of help will be really appreciated!
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double[] Statistics1 = new double[500];
double[] Statistics2 = new double[500];
double Alpha1;
double Alpha2;
double RV1;
double RV2;
Random random = new Random();
public double RandomDoubleInclusive() //We are using this method because random.NextDouble() method gives random number
//between 0 and 1 where 0 is inclusive and 1 is exclusive.
//Since the value of probability lies between 0 and 1, both inclusive that's why we need
//to use this method.
{
double d = 0.0;
int i = 0;
do
{
d = random.NextDouble();
i = random.Next(2);
}
while (i == 1 && d > 0);
return d + i;
}
private void label3_Click(object sender, EventArgs e)
{
}
int i,j;
private void button1_Click(object sender, EventArgs e)
{
int SampleSize = Convert.ToInt32(textBox3.Text);
for ( i = 0; i<500;)
{
for (j = 0; j < 500;)
{
Alpha1 = RandomDoubleInclusive();
Alpha2 = RandomDoubleInclusive();
double LnPart = Math.Log(Alpha1);
double part1 = (-2) * LnPart;
double part2 = 2 * 3.14159 * Alpha2;
double CosPart = Math.Cos(part2);
double SinPart = Math.Sin(part2);
RV1 = Math.Sqrt(part1) * CosPart;
Statistics1[i] = RV1;
RV2 = Math.Sqrt(part1) * SinPart;
Statistics2[j] = RV2;
i++;
j++;
}
}
var myList = new List<double>();
myList.AddRange(Statistics1);
myList.AddRange(Statistics2);
double[] arr3 = myList.ToArray();
double Max = arr3.Max();
double Min = arr3.Min();
double differenceofMaxMin = Max - Min; //calculating size of width of interval
double k;
k = Math.Log(SampleSize,2) + 1; //calculating number of subintervals
}
}
I'm not sure I fully understand what exactly you're trying to achieve, but I can certainly try to help you out with an example on how to split an array arr3 into k subintervals with (max) number of elements differenceofMaxMin
var arr3 = Enumerable.Range(0, 1000);
// given: the max number of elements
var differenceofMaxMin = 300;
// determine the number of subintervals
// note that the last subinterval may contain less than differenceofMaxMin elements
var k = (int)Math.Ceiling((double)arr3.Count() / differenceofMaxMin);
var arr3_split = Enumerable.Range(0, k)
.Select(i => arr3.Skip(i * differenceofMaxMin).Take(differenceofMaxMin));
Looking at your method to generate a random double from [0, 1], I think it's overkill since the likelihood to actually draw exactly 1.0 is extremely low.

Find all match positions in SIMD Avx.CompareEqual, or for a whole array while counting matches

I have a question if this is possible using SIMD instructions at all or if there could be some kind of Hybrid solution SIMD/Normal C# code solution to what I am trying to do or if it is not possible and will sacrifice to much speed of the SIMD instructions for it to be interesting.
My code counts how many 0,1,2,3 that exists in: inputArray (Micro Optimization of a 4-bucket histogram of a large array or list). Result is shown in: countArray
The correct answer to this is: 3,9,1,3.
My question now is this:
As seen we also have passed along: indexArray to the function. If we take 0 from inputArray as an example where we have 3 occurrences. We can see in the indexArray that those occurrences are at indexes: 9,43,5
I wonder if it is possible to add/collect this information in for example 4 buckets as well for each of the possible element values (0,1,2,3) in inputArray?
In the below code part we can see where the indexes for example: val = 1 is found: 0,9,10
I don't know if it is possible to catch those indexes somehow that could map/get the indexes from the indexArray?
The main goal to for example: ´0´ is to get an array in the end like this:
int[] indexes0 = new int[3]; //But we dont know that it will be 3 beforehand
indexes0[0] = 9;
indexes0[1] = 43;
indexes0[2] = 5;
[1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0]
// accumulate match counts into 4 vectors of 8-bit counters, one for each val
var v = Avx.LoadVector128(&fixedInput[0]);
for (byte val = 0; val < 4; val++)
{
//[1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0] -CompareEqual to: [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
var match = Avx.CompareEqual(v, Vector128.Create(val));
counts[val] = Avx.Subtract(counts[val], match); // count -= 0 or -1
}
(Please note: I have a Piledriver CPU that can't run AVX2)
Complete Code (simplified for an array that's only one vector-width long):
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
private void button3_Click(object sender, EventArgs e)
{
//Create 16 indexes with numbers between: 0-3. The goal is to count how many of those occurences we have for the numbers: 0-3
byte[] v1 = new byte[16]; int[] v2 = new int[16];
v1[0] = 0; v2[0] = 9;
v1[1] = 1; v2[1] = 12;
v1[2] = 2; v2[2] = 55;
v1[3] = 3; v2[3] = 23;
v1[4] = 1; v2[4] = 568;
v1[5] = 1; v2[5] = 4;
v1[6] = 1; v2[6] = 6;
v1[7] = 1; v2[7] = 1008;
v1[8] = 1; v2[8] = 188800;
v1[9] = 0; v2[9] = 43;
v1[10] = 0; v2[10] = 5;
v1[11] = 3; v2[11] = 2;
v1[12] = 1; v2[12] = 1;
v1[13] = 1; v2[13] = 58;
v1[14] = 1; v2[14] = 8;
v1[15] = 3; v2[15] = 15;
/*---------------*/
ReadOnlySpan<byte> inputArray = v1;
ReadOnlySpan<int> indexArray = v2;
//Call function
countElements(inputArray, indexArray);
}
// simplified for inputArray.Count == 16 exactly, no looping or cleanup
// shows counts, doesn't find positions at all
private unsafe static void countElements(ReadOnlySpan<byte> inputArray, ReadOnlySpan<int> indexArray)
{
int[,] indexes0123 = new int[,] { }; //Store arrays for indexes found for the numbers: 0,1,2,3 in the "indexArray"
//Below starts the SIMD calculations!
int[] countArray = new int[4];
Span<Vector128<byte>> counts = stackalloc Vector128<byte>[4];
Span<Vector128<UInt64>> sum64 = stackalloc Vector128<UInt64>[4];
unsafe
{
fixed (byte* fixedInput = inputArray)
{
var v = Avx.LoadVector128(&fixedInput[0]);
for (byte val = 0; val < 4; val++)
{
//[1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0] -CompareEqual to: [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
var match = Avx.CompareEqual(v, Vector128.Create(val));
counts[val] = Avx.Subtract(counts[val], match);
}
//Here SumAbsoluteDifferences
for (int i3 = 0; i3 < 4; i3++)
{
sum64[i3] = Sse2.Add(sum64[i3], Sse2.SumAbsoluteDifferences(counts[i3], Vector128<byte>.Zero).AsUInt64()); //sum64: <2,0,0,0,3,0,0,0>
}
//UnpackHigh and get the lower element from the Vector128<UInt64>
for (int i3 = 0; i3 < 4; i3++)
{
Vector128<UInt64> upper = Sse2.UnpackHigh(sum64[i3], sum64[i3]).AsUInt64(); //3
countArray[i3] += Sse2.Add(sum64[i3], upper).ToScalar();
}
//We now know how many 0,1,2,3 we have of each: (But we also need to collect which indexes from "indexlist" each of these 4 buckets has)
//3,9,1,3
MessageBox.Show(countArray[0] + "," + countArray[1] + "," + countArray[2] + "," + countArray[3]);
}
}
}

C# - Calculation in for loop not doing a correct calculation?

The program doesn't calculate/display the correct calculation/number correctly
I'm trying to learn some C# for Unity game development, and tried out some random math stuff, but something seems to not work and I can't figure out why.
Console.WriteLine("What is the total amount you'd like change for? For example: 41,15");
double change = Convert.ToDouble(Console.ReadLine());
// 500 200 100 50 20 10 5
// 2 1 0,50 0,20 0,10 0,05
int fivehundred = 0, twohundred = 0, onehundred = 0, fifty = 0, twenty = 0, ten = 0, five = 0;
int ctwo = 0, cone = 0, cfifty = 0, ctwenty = 0, cten = 0, cfive = 0;
for (int i = 0; change >= 500; i++)
{
change -= 500;
fivehundred++;
}
for (int i = 0; change >= 200; i++)
{
change -= 200;
twohundred++;
}
for (int i = 0; change >= 100; i++)
{
change -= 100;
onehundred++;
}
for (int i = 0; change >= 50; i++)
{
change -= 50;
fifty++;
}
for (int i = 0; change >= 20; i++)
{
change -= 20;
twenty++;
}
for (int i = 0; change >= 10; i++)
{
change -= 10;
ten++;
}
for (int i = 0; change >= 5; i++)
{
change -= 5;
five++;
}
for (int i = 0; change >= 2; i++)
{
change -= 2;
ctwo++;
}
for (int i = 0; change >= 1; i++)
{
change -= 1;
cone++;
}
for (int i = 0; change >= 0.50; i++)
{
change -= 0.50;
cfifty++;
}
for (int i = 0; change >= 0.20; i++)
{
change -= 0.20;
ctwenty++;
}
for (int i = 0; change >= 0.10; i++)
{
change -= 0.10;
cten++;
}
for (int i = 0; change >= 0.05; i++)
{
change -= 0.05;
cfive++;
}
Console.WriteLine("500x {0}, 200x {1}, 100x {2}, 50x {3}, 20x {4}, 10x {5}, 5x {6}, 2x {7}, 1x {8}, 0,50x {9}, 0,20x {10}, 0,10x {11}, 0,05x {12}", fivehundred, twohundred, onehundred, fifty, twenty, ten, five, ctwo, cone, cfifty, ctwenty, cten, cfive);
Even though there's still 5 cents left, the result gives me is this:
(this is when I entered 0,15 cents)
What is the total amount you'd like change for? For example: 41,15
0,15
500x 0, 200x 0, 100x 0, 50x 0, 20x 0, 10x 0, 5x 0, 2x 0, 1x 0, 0,50x 0, 0,20x 0, 0,10x 1, 0,05x 0
Press any key to continue . . .
If it's €0,09 or below, it does display that it needs 0,05 1x, but with anything above it with a remaining 5 cents, it doesn't. Everything else works as intended so far though.
(Also, any tips how I can make the code more efficient?)
I think this is what you are trying to do, but instead of using division, you are doing successive subtractions.
class Program
{
static void Main(string[] args)
{
int[] change = Currency.MakeChange(41.37m);
decimal sum = 0m;
for (int i = 0; i < change.Length; i++)
{
var amount = change[i]*Currency.Denominations[i];
sum += amount;
Debug.WriteLine($"{change[i]}×{Currency.Denominations[i]}");
}
Debug.WriteLine($"sum={sum}");
// output:
// 0×500
// 0×200
// 0×100
// 0×50
// 2×20
// 0×10
// 0×5
// 0×2
// 1×1
// 0×0.5
// 1×0.2
// 1×0.1
// 1×0.05
// 2×0.01
// sum=41.37
}
}
public class Currency
{
public static readonly decimal[] Denominations =
new decimal[] { 500m, 200m, 100m, 50m, 20m, 10m, 5m, 2m, 1m, 0.5m, 0.2m, 0.1m, 0.05m, 0.01m };
public static int[] MakeChange(decimal value)
{
int[] change = new int[Denominations.Length];
decimal remain = value;
for (int i = 0; i < Denominations.Length; i++)
{
// get the next note (amount in currency).
// must move from highest to smallest value.
decimal note = Denominations[i];
// can you divide the remainder with the note
int qty = (int)(decimal.Floor(remain/note));
change[i] = qty;
// calculate remaining amount
remain -= qty*note;
}
return change;
}
}
First of all, yes, you can simplify your code by A LOT just by replacing the for loops with while loops.
Second, to answear your actual question. The program does not enter the for loops because 0.05 it's not actually 0.05 because of how computers store floating point values in memory. EX.: 1/3 != 0.333333. To prevent this use the decimal data type.
Better explanation here and in the official C# Docs here under Precision in Comparisions.
Your code works as-is if you change from double to type decimal. There is a rounding error that occurs when using double precision, when I ran it 15-10 came out to 0.4999999999. Decimal has greater precision, so I would start there. You can figure this out either by setting breakpoints in your loops and stepping through them, or by adding Console.Writeline(change) in each loop so you can see what is happening. The debugger is your friend. That being said, lets clean up this code
Console.WriteLine("What is the total amount you'd like change for? For example: 41,15");
decimal change = Convert.ToDecimal(Console.ReadLine());
// 500 200 100 50 20 10 5
// 2 1 0,50 0,20 0,10 0,05
decimal[] currencyValues = {500m, 200m, 100m, 50m, 20m, 10m, 5m, 2m, 1m, .50m, .20m, .10m, 0.05m};
int[] returnChange = new int[13];
for(int i = 0; i < currencyValues.Length; i++)
{
if(change >= currencyValues[i])
{
returnChange[i] = (int)(change / currencyValues[i]);
change = change % currencyValues[i];
}
Console.Write($"{currencyValues[i]}x {returnChange[i]} ");
}
We can make use of arrays so we don't have to duplicate so much. So we have one array that holds the values of each denomination of currency, and then another array for the count of each denomination in the resulting change. Then we can go through each currency amount and do our calculations in one loop.
So first, we check to make sure we have at least as much change as the amount we are checking against. No need to calculate how many currency of value 5 we need to return if they only have 3, for example. Thats pretty intuitive so lets move on to the next part.
First, we divide the change left by each currency value. We only want whole numbers, we can't give someone half of a coin, after all. So we cast to integer to round the result and make it fit into our returnChange array. The next part is probably gonna look weird if you haven't seen the modulo operator % before. This basically says
Perform the division. But, rather than assigning the result of the division, assign the `remainder` instead
So if we have .70 currency, and we took out .50 for the change, the modulo % operator will say we have .20 currency remaining.
Hope this helped.
Refactor common code into reusable components. For example, your logic to calculate the count of a denomination is the same except for the denomination value and remaining balance, so create a function to abstract that logic:
// `ref` passes the decimal value in by reference, meaning any
// changes made to that parameter are also made to the variable
// passed into the method/function (by default a copy is made
// and changes here have no side effects
public int CashOut(decimal denomination, ref decimal balance)
{
var result = 0;
for (int i = 0; change >= denomination; i++)
{
balance -= denomination;
result++;
}
return result;
}
As a comment pointed out, a for loop isn't ideal here - you're not using
the variable i at all; a while loop is more appropriate:
public int CashOut( decimal denomination, ref decimal balance )
{
var result = 0;
while( balance >= denomination )
{
balance -= denomination;
++result; // preincrement operator has better performance
}
return result;
}
There are still better ways to perform your desired calculation; as another
answer pointed out, you can use division:
public int CashOut( decimal denomination, ref decimal balance )
{
var result = Convert.ToInt32( balance / denomination );
balance -= result * denomination;
return result;
}
If you didn't abstract the calculation changes, each change would require you to edit your N for loops; with this abstraction, you only have to edit it in a single place.
Replacing your for loops would look something like:
fivehundred = CashOut( 500.0M, ref change );
twohundred = CashOut( 200.0M, ref change );
// etc.
But that's still highly repetitive. As another answer and comment pointed out, you can configure an array of denominations (and results) to process sequentially:
var denominations = new[]{ 500.0M, 200.0M, 100.0M }
var results = new int[denominations.Length];
for( var i = 0; i < denominations.Length; ++i )
{
results[i] = CashOut( denominations[i], ref change );
}
But you don't need that for loop if you use LINQ!
var denominations = new[]{ 500.0M, 200.0M, 100.0M };
var results = denominations.Select( d => CashOut( d, change ) )
.ToArray();
Your output could then be written as:
for( var i = 0; i < denominations; ++i )
{
Console.Write( $"{denominations[0]}x {results[i]} " )
}
Console.WriteLine();
How about projecting an anonymous type to keep the denomination paired with its result?
var denominations = new[]{ 500.0M, 200.0M, 100.0M };
var results = denominations.Select( d =>
new
{
Denomination = d,
Count = CashOut( d, change ),
} );
Then your output could look like:
foreach(var result in results)
{
Console.Write( $"{result.Denomination}x {result.Count} " );
}
Console.WriteLine();
If you wanted to find out how many 200's were in the results, you can find it easily:
var twoHundreds = results.FirstOrDefault(r => r.Denomination == 200.0M)
?.Count // ?. means execute the following statement(s) if the value is not null
?? 0M; // ?? is the null coalescing operator meaning return this value if the precedeing is null

Issues with looping code and do-while loops (c#)

static double calculateTotals(double a)
{
double transfee = a * .01;
double total = a + transfee;
return total;
}
static void Main(string[] args)
{
Console.WriteLine("How many dontations to process?");
int donations = Convert.ToInt16(Console.ReadLine());
int[] count = new int[] { donations + 1 };
int ct = 1;
int i = -1;
do
{
Console.WriteLine("Enter name: ");
string name = Console.ReadLine();
Console.WriteLine("Enter donation amount: ");
double amount = Convert.ToDouble(Console.ReadLine());
double transfee = amount * .01;
i++;
ct = count[i += 1];
Console.WriteLine(name + "\t" + amount + "\t" + transfee);
} while (i < donations);
Console.WriteLine("TOTALS:" + "\t" + calculateTotals(amount) + "\t" + transfee);
Console.ReadLine();
}
}
Hello. I am a beginner at coding, so I apologize if this is a poor attempt.
I am trying to make an app that records the amount donated by an individual, calculates a transaction fee, and outputs the results for each person. At the end, I am creating a final row of output that will state the total donations and the total transaction fees.
I am currently unsure how to properly implement the array into my loop, and am unsure if the loop is optimized in general.
Again, I am a beginner. I apologize for such code, but I'd love some clarification on these things.
Thank you!
First, your array declaration syntax is wrong. See this link.
So it should be int[] count = new int[donations+1];
Second, you need to declare and instantiate your amount and transfee variables outside of your loop.
double transfee = 0.0F;
double amount = 0.0F;
do
{
...
amount = Convert.ToDouble(Console.ReadLine());
transfee = amount * .01;
...
} while (i < donations);
This should be enough information to get you going again. Since you're learning, I don't think anyone would really unfold an answer for you that does the job you're trying to figure out :)
Your code :
int i = -1;
do
{
...
i++;
ct = count[i += 1];
...
} while (i < donations);
You are actually increase i two times, then get values from count[i] assign to ct variable
See this sample :
int[] count = new int[3];
count[0] = 0;
count[1] = 1;
count[2] = 2;
int i = -1;
do
{
i++;
int x = count[i += 1];
Console.WriteLine(x);
} while (i < 3);
It will cause IndexOutOfRangeException
Explain :
First Loop :
i++; // i increased 1, so i = 0
int x = count[i += 1]; // i increased 1, so i = 1, then get count[1] assign to x, x is 1
Second loop:
i++; // i increased 1, so i = 2
int x = count[i += 1]; // i increased 1, so i = 3, then get count[3] assign to x
count[3] cause IndexOutOfRangeException
Something like count[i += 1] will make your code more difficult to maintain, in my opinion, you should avoid it if possible, try to write it explicity as you can

How to subtract two numbers and add the result to the third number in a sequence?

I am trying to write a C# program that takes an input value from user and then puts that value inside a sequence, then prints the result of every calculated number of the sequence inside a listBox. the sequence is like this:
S = 1 - X + X^2 / 2! - X^3 / 3! + X^4 / 4! - ...
First number that will be shown inside the listBox every time the program starts is 1. i am stuck at the part where i should subtract 1 from the user input (X) and then add the result to the third calculated number of the sequence. For example if user enters 2 as input, first output is 1, second output is -1 and then the program should add the result (-1) to the third calculated number of the sequence which is 2 and output should be 1. again subtract the result (1) from the fourth calculated number and again add the result to the fifth calculated number of the sequence and ...
so far i wrote this:
private void button1_Click(object sender, EventArgs e)
{
int x = Convert.ToInt32(textBox1.Text);
listBox1.Items.Clear();
listBox1.Items.Add("1".ToString());
double numerator = 1, Fact = 1, firstNum = 1, result;
for (int i = 1; i <= 20; i++)
{
numerator = x * numerator;
Fact = Fact * i;
result = numerator / Fact;
firstNum = firstNum - result;
listBox1.Items.Add(firstNum.ToString());
}
But i can't figure out how to write the code for the parts of sequence that should add the result to the next calculated number. Above codes will only subtract the result from next number and prints the result, but now how to add the result of subtraction to the next number and prints it again to the listbox?
First number of sequence - Second number of sequence = Result (show in listbox)
Result + Third number of sequence = Result (show in listbox)
Result - Fourth number of sequence = Result (show in listbox)
Result + Fifth number of sequence = Result (show in listbox)
I am very sorry if i explained the problem bad, i tried to be as specific as possible. I know i'm missing a very tiny piece, but i can't figure out what is it, and sorry for the writing, english is not my native language.
Thanks in advance
You are almost on the right track. Just missing few things.
Here is the corrected version of your program --->
private void button1_Click(object sender, EventArgs e)
{
int x = Convert.ToInt32(textBox1.Text);
listBox1.Items.Clear();
listBox1.Items.Add("1".ToString());
double numerator = 1, Fact = 1, firstNum = 1, result=0;
for (int i = 1; i <= 20; i++)
{
Fact = 1; // Reinitialising every time for new denomerator.
numerator = Math.Pow(x, i); // This is how power is calculated.
for (int j = 1; j<=i; j++) // One more inner loop is needed for Factorial.
Fact = Fact * j;
result = numerator / Fact;
firstNum = firstNum + (Math.Pow(-1, i) * result); // This is the main logic for alternate plus minus.
listBox1.Items.Add(firstNum.ToString());
}
}
I hope it solves your problem. :)
Maybe try to store the result of the subtraction(firstNum - result) to a variable and then add it to the next number?
Looks like the sequence formula is
f(i) = (-x)^i / i! for i in 0..N, 0! = 1
which can be produced as follows
private void button1_Click(object sender, EventArgs e)
{
int x = Convert.ToInt32(textBox1.Text);
listBox1.Items.Clear();
double numerator = 1, denominator = 1;
int i = 0;
while(true)
{
var result = numerator / denominator;
listBox1.Items.Add(result.ToString());;
if (++i > 20) break;
numerator *= -x;
denominator *= i;
}
}
var seqLimit = Convert.ToInt32(Textbox1.Text);
var numberX = Convert.ToInt32(XTextBox.Text);
ListBox1.Items.Clear();
var result = 1.0;
for (var i = 1; i <= seqLimit; i++)
{
ListBox1.Items.Add(result);
if (i%2 == 0) result = result + (Math.Pow(numberX, i)/Factorial(i));
else result = result - (Math.Pow(numberX, i)/Factorial(i));
}
static int Factorial(int n)
{
if (n <= 1)
return 1;
int result = 1;
for (int i = 2; i <= n; i++)
{
result = result * i;
}
return result;
}
Try this, it would work.

Categories

Resources