Round a given float number n according to the "Round half up" algorithm with a given number of decimal places m.
More about rounding here.
from decimal import Decimal, ROUND_HALF_UP
def roundHalfUp( n, m ):
return float( Decimal( str( n ) ).quantize( Decimal( "1." + "0" * m ), rounding = ROUND_HALF_UP ) )
test.assert_equals( roundHalfUp( 2.5, 0 ), 3 )
test.assert_equals( roundHalfUp( 3.5, 0 ), 4 )
test.assert_equals( roundHalfUp( 2.535, 2 ), 2.54 )
test.assert_equals( roundHalfUp( 2.525, 2 ), 2.53 )
test.assert_equals( roundHalfUp( 2.5, 2 ), 2.5 )
test.assert_equals( roundHalfUp( 2.59999, 2 ), 2.6 )
test.assert_equals( roundHalfUp( 2.58499, 2 ), 2.58 )
test.assert_equals( roundHalfUp( 2.425, 2 ), 2.43 )
test.assert_equals( roundHalfUp( 2.435, 2 ), 2.44 )
test.assert_equals( roundHalfUp( 2.446, 2 ), 2.45 )
test.assert_equals( roundHalfUp( 2.444, 2 ), 2.44 )
test.assert_equals( roundHalfUp( 2.4445, 2 ), 2.44 )
test.assert_equals( roundHalfUp( 2.3435, 2 ), 2.34 )
test.assert_equals( roundHalfUp( 2.3415, 2 ), 2.34 )
def real_cube_root( n ): return (1 if n >= 0 else -1) * (abs( n ) ** (1 / 3))
def real_cube_root(n):if n >= 0: return n ** (1/3)else: return -abs(n ** (1/3))- def real_cube_root( n ):
- return (1 if n >= 0 else -1) * (abs( n ) ** (1 / 3))
test.assert_equals( real_cube_root( 0 ), 0 ) test.assert_equals( real_cube_root( 5 ), 5 ** (1 / 3) ) test.assert_equals( real_cube_root( -5 ), -5 ** (1 / 3) ) test.assert_equals( real_cube_root( -50 ), -50 ** (1 / 3) ) test.assert_equals( real_cube_root( -105 ), -105 ** (1 / 3) )
- test.assert_equals( real_cube_root( 0 ), 0 )
- test.assert_equals( real_cube_root( 5 ), 5 ** (1 / 3) )
- test.assert_equals( real_cube_root( -5 ), -5 ** (1 / 3) )
- test.assert_equals( real_cube_root( -50 ), -50 ** (1 / 3) )
- test.assert_equals( real_cube_root( -105 ), -105 ** (1 / 3) )