# Calculation

I got one calculation

Where magnet and magnetpos are integers, does this mean that this calculation is faster then, when i declare magnet and magnetpos as floats or do i need to change the code to make it faster?

magnet=((magnetpos-405)/8.55);

I know that i got diving by fraction number, so it means this magnet is float but it is later on converted to integer?

It would be hard to tell the difference between that code with magnet/magnetpos as ints and floats. As ints it will be ever so slightly faster because the subtract is an integer operation if ints, and as a float operation as floats. Although the int version suffers two float/int conversions, so that will offset somewhat.

That said, the Arduino chip is fast. It's very rare where a change like this will produce noticeable results.

If magnet and magnetpos are integers, (magnetpos - 405) will be an int. Dividing an int by a float results in a float. That float is then stored in an int, truncating any fractional portion.

Subtraction is not significantly affected by the float/integer choice. Division is faster if the dividend and divisor are both ints. Of one is a float (like 8.55), floating point division is performed.

Multiplying the subtraction result by 100, then dividing by 855 would be faster, as integer division is performed as long as the multiplication operation produces an int sized value.

PaulS:
Multiplying the subtraction result by 100, then dividing by 855 would be faster, as integer division is performed as long as the multiplication operation produces an int sized value.

thats what i was planning to do.

Thank you PaulS,Maniacbug for answering so fast! I got answer to my question.

As pointed out the formula uses float math, especially the division costs time, easily to be replaced by a multiplication

magnet=((magnetpos-405)/8.55);

magnet = (magnetpos-405) * 0.116959064;

but you can transfer the math to in integer domain to make it faster

magnet = (magnetpos - 405) * 20/171; // 171/20 = 8.55

As I don't know the minimum and maximum value of magnetpos you might need to declare them (unsigned) long to prevent overflow if magnet and magnetpos are declared as (unsigned) int.

2 cents,