Message Boards Message Boards

0
|
4236 Views
|
2 Replies
|
1 Total Likes
View groups...
Share
Share this post:

How do I obtain the sum of all iterations of a loop?

Posted 5 years ago

I'm new to loops and I've been trying to figure out how to tell Mathematica how to add up all of the outputs from a loop that I've created. I haven't seen any example similar to what I'm doing despite it being fairly basic (I'm new to this how complex could it be). The loop that I've made uses the counter within the equation so maybe that is why I'm having trouble. Each iteration consists of the sum of the square of an odd number plus one minus the square of the next odd number below it (3+1)^2 - 1^2). What I can't figure out is how to get each iteration to add up with the previous ones, either I just get the list of the outputs, or I just get a list of 39 (this seems to be related to the wolfram kernel which I have to delete every time I run this). This is the code I have any tips would be appreciated.

a = x^2;
b = (x + 1)^2;
c = b - a;
For[x = 1; sum = c, x <= 17, x += 2, sum = c + c; Print[c]]
POSTED BY: Chris Agee
2 Replies
Posted 5 years ago

Thank you for the quick response, I was so myopically focused on using loops, that a table never even occurred to me! This is a much better solution, thanks!

POSTED BY: Chris Agee

Chris,

Mathematica (MMA) is a list based language and looping is generally slow and "clunky" in MMA. You should try to formulate using lists.

  1. To fix the kernel reset each time, just put a Clear[x]; before your loop (but I would not use a loop).

  2. Use Table instead

    result = Table[c,{x,1,17,2}]
    

This creates a list of c values for x's ranging from 1 to 17 incrementing by 2.

To total it you can create a list of Accumulations or use Total

Accumulate[result]

{3, 10, 21, 36, 55, 78, 105, 136, 171}

Or Total

Total[result]
171

Regards,

Neil

POSTED BY: Neil Singer
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract