I am a hobbyist programming for an embedded application. The application requires speed. I would like to determine whether or not a certain variable (call it “X”) has passed a certain percentage (call it “Y”) of another variable (call it “Z”).
X, Y, and Z can all change at runtime. Since I need speed I would like to do this using integer math as opposed to float, which incurs a speed penalty.
Are there any tricks for doing this? I am a self trained programmer so please excuse me if this is a well known problem with a well known solution.
Thank you!
So what you want is to test
1*X > Z*Ythere is nothing stopping you from doing exactly this, simply define 1 (and thus 100%) to be10^decPlaceswheredecPlaces>=2(otherwise you won’t have enough precision to do percentages asintsif you need calculations to be correct to within 4 d.p. if
X = 10thenX_fixed_precision = 100000if Y is 30% (0.3) thenY_fixed_precision=3000and ifZ=10000thenz_fixed_precision=100000000this trick is called fixed precision arithmetic…If you want even better performace use powers of 2 instead of 10 (its harder to translate into exactly how many decimal places this gets you but should be somewhat faster)
e.g. your code would probably look like
where
FOO_fixed_precision = FOO * ONE_FIXED_PRECISIONBe careful to ensure that you aren’t going to get integer overflow there though – the Max value of
X * ONE_FIXED_POINT * ONE_FIXED_POINTmust be less than the maximum value you can store in a word (or double word if your using longer integer types)