Code:
#COMPILE EXE #DIM ALL '--------------------------------------------------- ' Round-Half-Up - Round EXT to LONG '--------------------------------------------------- ' The tricky point is what "up" means for negative numbers. Does it mean increasing ' in size towards negative infinity? Or does it mean increasing towards positive ' infinity? If it means increasing towards negative infinity then the algorithm ' is 'symmetric' with respect to zero for positive and negative values. If it means ' increasing towards positive infinity then the algorithm is 'asymmetric' with ' respect to zero for positive and negative values. ' .NET Math.Round(x, System.MidpointRounding.AwayFromZero) is symmetric. ' Python round() is symmetric. ' MATHLAB round() is symmetric. ' Java round() is assymmetric. '--------------------------------------------------- FUNCTION RoundHalfUp_S (BYVAL extVal AS EXT) AS LONG ' symmetric implementation (-5.5 rounds to -6) FUNCTION = FIX(extVal + (SGN(extVal) * 0.5##)) END FUNCTION '--------------------------------------------------- FUNCTION RoundHalfUp_A(BYVAL extVal AS EXT) AS LONG ' asymmetric implementation (-5.5 rounds to -5). FUNCTION = FIX(extVal + IIF(SGN(extVal)=1, 0.5##, 0.0##)) END FUNCTION '--------------------------------------------------- FUNCTION PBMAIN() AS LONG LOCAL x AS EXT STDOUT "Symmetric" FOR x = 9.5## TO -9.5## STEP -0.5## STDOUT FORMAT$(x, "0.0") & " = " & FORMAT$(RoundHalfUp_S(x), "0") NEXT x STDOUT STDOUT "Asymmetric" FOR x = 9.5## TO -9.5## STEP -0.5## STDOUT FORMAT$(x, "0.0") & " = " & FORMAT$(RoundHalfUp_A(x), "0") NEXT x STDOUT $CRLF & "Press any key to exit ... "; WAITKEY$ STDOUT END FUNCTION
Comment