# Math in a Loop Assist?

Question asked by nclark4 on Sep 8, 2018
Latest reply on Sep 9, 2018 by philmodjunk

I have a relatively simple math problem I have been spinning wheels on and would appreciate advice as I know I'm missing something basic.  I am relatively new to FM, using FMPA 17.  The user will enter a total start weight on the parent table, Order.  The attached script splits the start weight among any number (0-16 usually) of line items on the child table, OrderItems, into the SW_test field based on percents that have already been entered.  Basic business rules:

• The total start weight has to be stored on the Order table (so as I understand it, it cannot be a global).
• Not all OrderItems require a weight split, so I have a flag set to assist this (an item cannot be in the Additions category but will have quantityunit=%; if true it has a 1 in the cCountStartWeight field).
• There is no precedence to how the weight is split among line items for close percents, but the numbers in SW_test do have to be a positive integer (no decimals).  Put another way, it doesn't matter if the first or the last item gets any "leftover" if they have the same or similar percents.  In the image, 15-87 could have 2 or 15-91 could (instead of the current 1) or really any in-between those two given the closeness.  The overage needs to land somewhere.
• More a practice than a rule but I am using SW_test to store results until I get it working correctly, as StartWeight is from when it was done manually so can be a rudimentary check.

I currently split the loop into numbers evenly divisible (top half in split1 attachment--this part works) and odd, although I know divisibility rules are more complex than that but I thought I would tackle that if it came up.  The split2 part of the loop is not balancing out the numbers correctly.  I've tried several variations on the formula in \$Each (which is why there are some unused var in there) but none have worked and I am either under or over.  The total manual start weight in the below example is 63 but SW_test adds to 62.  I'm open to suggestions if I can streamline the script overall too--as I said I'm new so figuring this out.  The image is line items from just one order; they can vary widely.  Thanks!