简体   繁体   中英

How to compute percentage using fixed point arithmetic?

I'm trying to compute the percentage of dropped packets uisng fixed point arithmetic:

dropped packets/(dropped packets + transmitted packets)

A packet can either be transmitted or it can be dropped. The above formula will provide the percent of packets that got dropped.

The problem is I am doing this on a fix point architecture (no floating point allowed). The best I have been able to come up with is this:

(100*dropped packets)/(dropped packets + transmitted packets)

This will work but there are a couple problems with it. It only gets me accuracy to plus or minus 1%. You also have to worry about overflow issues.

This must be a pretty common problem; I was wondering if there was a better way of doing this?

OP method gives an "accuracy to plus 0% or minus 1%" rather than "plus or minus 1%". To get +/- 0.5% use (100*dp + (dp+tp)/2)/(dp + tp). Note: integer division truncates, not rounds.

To get better, simple *1000, *10000, etc.

To avoid overflow, use unsigned long long , uint64_t or uintmax_t .

Example: (per thousand)

unsigned long long DroppedPerThousand(unsigned dropped, unsigned transmitted) {
  unsigned long long sum = dropped;
  sum += transmitted;
  return (1000ULL*dropped + sum/2)/sum;
}

This could be re-written as a macro.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM