Andy
Andy

Reputation: 183

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?

Upvotes: 2

Views: 907

Answers (1)

chux
chux

Reputation: 153517

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.

Upvotes: 3

Related Questions