Re: Procedure for percent of a value



In article <47c8207c$1_4@xxxxxxxxxxxxxxx>,
Simon Bachmann <ssiimmoonnbbaacchhmmaannnn@xxxxxxxxxxxxxxxxxxx> wrote:
Marcos Martinez Sancho wrote:
Hello,

I need a small procedure for calculate the percent of a value

e.g.


set srate [expr int(($tps_ok / $number_of_total_tps)*100)]

puts "\nTEST RESULT: $number_of_total_tps tps of which $tps_ok PASSED and
$tps_nok FAILED so $srate % succes rate"


doesnt look optimal and is not working except when srate = 100%. Otherwise,
I get 0%.

When both numbers in a division operation are are integer, [expr]
performs an integer division. That means that only the integer part of
the result is calculated, no "comma part":

% expr 10/3
3
%

And since srate < 100% means that tps_ok is less than
number_of_total_tps, the $tps_ok / $number_of_total_tps will always give
0 as result.

The solution is to make one of the values a floating point value, all
other numbers will be "coerced" into floating point numbers too. Usually
it's done like this:

set srate [expr int((1.0 * $tps_ok / $number_of_total_tps)*100)]
.
.
.
'Everybody understand that floating point calculations are NOT
required? Depending on the domains of the variables, it might
well be advantageous to write

expr (100 * $tps_ok) / $number_of_total_tps
or
expr ((200 * $tps_ok) + 1) / (2 * $number_of_total_tps)

or several other variations.

Computer arithmetic's harder'n it looks--but not impossible.
.



Relevant Pages

  • Re: Procedure for percent of a value
    ... old fogies who have done a lot of work on integer only systems is ... to multiply first ie.g. ... doesnt look optimal and is not working except when srate = 100%. ... The solution is to make one of the values a floating point value, all other numbers will be "coerced" into floating point numbers too. ...
    (comp.lang.tcl)
  • Re: Procedure for percent of a value
    ... Marcos Martinez Sancho wrote: ... doesnt look optimal and is not working except when srate = 100%. ... performs an integer division. ... The solution is to make one of the values a floating point value, all other numbers will be "coerced" into floating point numbers too. ...
    (comp.lang.tcl)
  • Re: Procedure for percent of a value
    ... $tps_nok FAILED so $srate % succes rate" ... doesnt look optimal and is not working except when srate = 100%. ... You need to ensure floating point division as others have indicated. ...
    (comp.lang.tcl)
  • Re: What to do when TCL is too precise?
    ... it's only used when floating pointer numbers are converted ... I would like to FORCE all intermediate calculations ... to have limited precision. ... % expr 1./3. ...
    (comp.lang.tcl)