# Arithmetic

How can I make this equation accurate? I believe its because the first 4 numbers in the equation results in a decimal. The answer should be 13,500 according to my calculator. The arduino is calculating it at 13,600.

long interval1 = (((45 * (100 - 25)) / 100)601000L) / (200 - 50);

(((45 * (100 - 25)) / 100)601000L) / 150

(((45 * 75) / 100)601000L) / 150

((3375 / 100)601000L) / 150

(33601000L) / 150

13200 ?

Are you using those actual numbers in the sketch, or are some of them variables?
A bit of rearranging will get rid of the fractional part:

``````long interval1 = ((45L * (100 - 25) * 60 * 1000) / 100) / (200 - 50);
``````

On 8 bit Arduinos, expressions like this are evaluated as 16 bit signed integers, using integer arithmetic. The result is 33

((45 * (100 - 25)) / 100)

The Arduino reports 13200 for "interval1".

Sorry. I had changed the 25 to 23. 25 is 13200.

All numbers are variables except this part "100)601000L)".

The suggestion of below may work:

long interval1 = ((45L * (100 - 25) * 60 * 1000) / 100) / (200 - 50);

If the last number was something like 57 it is still off. The result is closer and probably close enough. Its just for prolonged dimming of various lights. The interval is how long a light stays at each PWM setting. An hour cycle would only be a couple minutes off at most.

``````long interval1 = (((dimduration * percent) / 100)*60*1000L) / (maxbrightness - minbrightness);
long interval2 = (((dimduration * (100-percent)) / 100)*60*1000L) / (maxbrightness - minbrightness);
``````

tsperry88:
If the last number was something like 57 it is still off. The result is closer and probably close enough. Its just for prolonged dimming of various lights. The interval is how long a light stays at each PWM setting. An hour cycle would only be a couple minutes off at most.

What are you getting with 57, and what should the answer be?

The equation can be simplified a bit to eliminate one of the divisions:

``````  interval1 = (dimduration * percent * 600L) / (maxbrightness - minbrightness);
interval2 = (dimduration * (100 - percent) * 600L) / (maxbrightness - minbrightness);
``````

This works. I didnt think float variables could handle what I was doing.

``````  int minbrightness = 50;  // Lowest setting the bulb can output. (0-255)
int maxbrightness = 200; // Highest setting the bulb can output. (0-255)
int percent = 25;        // Percentage of dim duration that channel 2 finishes. (0-100)
float interval1 = ((dimduration * ((100 - percent) * .01))*60*1000) / (maxbrightness - minbrightness);
float interval2 = ((dimduration * (percent * .01))*60*1000) / (maxbrightness - minbrightness);
``````