I am making a program that estimates pi through increasing the number of sides of a polygon with a given radius to an extremely high number, taking the area, and dividing it by the radius squared. I have the following:
double radius = 5;
for (double sides = 3;sides < 10000;sides++)
{
double pi_est = ((radius * radius * sides * Math.Sin((360 / sides)*(Math.PI/180))) / 2) / (radius * radius);
richTextBox1.AppendText(pi_est+"\n");
}
As of now, this takes about 5 seconds to complete. Is there anything I could re write that would improve the efficiency of my loop?
That
AppendTextcall is going to cost a lot of time because it implies accessing the UI. Accumulate the string using aStringBuilderor an array withString.Joininstead.You should never use a
doubleas an iteration variable; use anintinstead (that’s less of an efficiency problem and more of a potential gotcha).radius*radiuscancels out — note thatpiis independent of the radius used, so you can just assume the radius is equal to 1 and ignore it.All written out: