# Formula Help

I am trying to solve the number of steps required for a stepper motor using a simple formula. When I run the formula, the serial monitor prints -15536 which is not right. The answer should be 50,000. Can anyone help explain why I'm getting this result and what can I do differently?

``````// Formulas
int borePosition = 1000; // Input travel distance from start position. Must have same units as screwLead variable
int screwLead = 8; // Input the Lead of lead screw. Must have same units as borePosition variable
int microstepVal = 400; // Input the microstep setting that the motor driver is set to

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.print(calcPulseNum);

}
``````

50,000 - 2^16 = -15536 so I'd suspect an integer truncation error

On Arduino, multiplication is done using integer math by default.

Make your variables long or unsigned long.

Actually, however not knowing whether your program uses negative numbers, if the 16 bit variables were declared as unsigned int if possible it might also treat the 50,000 quantity normally. It all depends on how confident you are about the range of the input numbers.

Also, you might be losing precision in this line:

``````  long calcPulseNum = borePosition/screwLead*microstepVal;
``````

When doing this kind of scale arithmetic, it is preferable to do the multiplication(s) first, then any divides. It minimizes truncation of data which degrades its accuracy. Instead something like:

``````  long calcPulseNum = (long)borePosition*microstepVal/screwLead;
``````

Great! I made the long changes you guys suggested and that made all the difference. Aarg, thanks for the information about order of operations when coding an expression. Also, how come you have '(long)' in front of the expression? I wrote 'long' in front of each variable when defining them without putting '(long)' as you did, and the serial monitor printed the right value. I also got the right answer using your method. Is having '(long)' better in some way?