424,985 Members | 1,863 Online Need help? Post your question and get tips & solutions from a community of 424,985 IT Pros & Developers. It's quick & easy.

Using loops to find a convergence point in calculating an integral

 P: 1 I am attempting to write a loop that will use rudimentary methods to solve an integral (as in the area under a curve) to a certain user-specified degree of accuracy by calculating the area of a changing number of rectangles that fit along that curve. This is the code I have so far: Given a polynomial y=5x^5+x^4+2x^3-7x^2+x+2, and the start and end points 1, 5, the user inputs are: x5=5, x4=1, x3=2, x2=-7, x=1, c=2, s=1, e=5, and cL is the convergence limit saying that it must be accurate to .01. Expand|Select|Wrap|Line Numbers Function EC(x5, x4, x3, x2, x, c, s, e, cL) r = 10     Do         w = (e - s) / r         h = s + 0.5 * w             For n = 1 To r                 y = x5 * h ^ 5 + x4 * h ^ 4 + x3 * h ^ 3 + x2 * h ^ 2 + x * h + c                 area = y * w                 sum0 = sum0 + area                 h = h + w             Next n         r = r * 2         w = (e - s) / r         h = s + 0.5 * w             For p = 1 To r                 y = x5 * h ^ 5 + x4 * h ^ 4 + x3 * h ^ 3 + x2 * h ^ 2 + x * h + c                 area = y * w                 Sum = Sum + area                 h = h + w             Next p          r = r * 10     Loop Until Sum - sum0 <= cL       EC = Sum   End Function So far it seems to work properly if the condition is met the first time through the loop, but if it has to go through a second time, it enters an endless loop, and I don't know why. This also makes me think that at least my math is correct and I am not making a silly mistake there, which leads me to believe I am missing something on the coding side. I would really appreciate any help-this problem has been driving me crazy all weekend. Thanks Oct 25 '14 #1
3 Replies

 Expert 100+ P: 1,208 hmm can you give me an example of parameters to this function that would cause an infinite loop? I tossed it in visual studio and passed it the parameters you specified in your post and it goes through the loop several times and the result ends up being 66418.75 Expand|Select|Wrap|Line Numbers Console.WriteLine(EC(5, 1, 2, -7, 1, 2, 1, 5, 0.01))   Oct 26 '14 #2

 Expert Mod 10K+ P: 12,349 You should be explicit in your variable declarations. You have some in your function that aren't defined anywhere. And if they're not defined, then they might be pulling their value from a wider scope when you don't intend them to. And if they're pulling their value from outside the scope of the function, then you have values persisting that can mess with the function call. Oct 26 '14 #3

 Expert 100+ P: 1,208 I forgot to mention that, I casted all the variables to singles since you didn't define them in your post. Oct 26 '14 #4 