开发者

Looking for good substitute for calculating percentage employing integer math

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 th开发者_如何转开发ere 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*Y there is nothing stopping you from doing exactly this, simply define 1 (and thus 100%) to be 10^decPlaces where decPlaces>=2 (otherwise you won't have enough precision to do percentages as ints

if you need calculations to be correct to within 4 d.p. if X = 10 then X_fixed_precision = 100000 if Y is 30% (0.3) then Y_fixed_precision=3000 and if Z=10000 then z_fixed_precision=100000000 this 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

if (ONE_FIXED_PRECISION * X_fixed_precision > Z_fixed_precision * Y_fixed_precision)
   // Do something

where FOO_fixed_precision = FOO * ONE_FIXED_PRECISION

Be careful to ensure that you aren't going to get integer overflow there though - the Max value of X * ONE_FIXED_POINT * ONE_FIXED_POINT must be less than the maximum value you can store in a word (or double word if your using longer integer types)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜