Hello all,

 

Isn't the better approach just to use floating point, which handles all the
scaling and stuff automatically, as well as making rounding really simple?
The fact that it's taken us a couple of at-bats to find the right solution
that avoids integer under/overflow and divide by zero suggests that the
alternate solution that clearly and succinctly represents the algorithm
carries a +1 all its own.

 

I ran a bunch of tests with this very function, looking at edge cases, and
it consistently got the right values, including handling rounding correctly,
which the integer version did not.


static int _percent(unsigned long long value, unsigned long long total)

{

        if (total == 0 ) return 0;

 

        float pct = (value * 100.) / total;

 

        pct += 0.5;     /* rounding */

 

        return (int) pct;

}

 

There are other floats in that MIB, and I'd imagine that any compiler that
could handle "unsigned long long" could deal with a float.

 

Steve

 

From: Bart Van Assche [mailto:bvanass...@acm.org] 
Sent: Friday, September 02, 2011 9:54 AM
To: Dave Shield
Cc: Net-SNMP coders
Subject: Re: RFV: Disk calculation overflow

 

On Fri, Sep 2, 2011 at 11:42 AM, Dave Shield <d.t.shi...@liverpool.ac.uk>
wrote:

On 2 September 2011 06:56, Bart Van Assche <bvanass...@acm.org> wrote:
> The loss of precision for small values of "value" and "total" can be
> avoided by using the new formula only if these values are large.



Something like:


--- a/agent/mibgroup/ucd-snmp/disk_hw.c
+++ b/agent/mibgroup/ucd-snmp/disk_hw.c

@@ -248,7 +248,11 @@ static int _percent( unsigned long long value,

unsigned long long total ) {
    /* avoid division by zero */
    if (total == 0)
        return 0;

-    return (int)( value * 100 / total );

+    if (total < 10000 )

+        return (int)( value*100 / total );

+    else
+        /* Equivalent calculation, avoiding possible arithmetic overflow */

+        return (int)( value / (total/100) );
 }

 static netsnmp_fsys_info **


?
10000 is an arbitrary cut-off - it could be tweaked either way if necessary,
but seemed a reasonable starting point.


+1

Bart.

------------------------------------------------------------------------------
Special Offer -- Download ArcSight Logger for FREE!
Finally, a world-class log management solution at an even better 
price-free! And you'll get a free "Love Thy Logs" t-shirt when you
download Logger. Secure your free ArcSight Logger TODAY!
http://p.sf.net/sfu/arcsisghtdev2dev
_______________________________________________
Net-snmp-coders mailing list
Net-snmp-coders@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/net-snmp-coders

Reply via email to