[zurück]

2.9. Modul decimal

[vor]

Mit dem Befehl dir lassen sich alle Funktionen des Moduls decimal anzeigen.

print(dir(decimal)) ['BasicContext', 'Clamped', 'Context', 'ConversionSyntax', 'Decimal', 'DecimalException', 'DecimalTuple', 'DefaultContext', 'DivisionByZero', 'DivisionImpossible', 'DivisionUndefined', 'ExtendedContext', 'Inexact', 'InvalidContext', 'InvalidOperation', 'Overflow', 'ROUND_05UP', 'ROUND_CEILING', 'ROUND_DOWN', 'ROUND_FLOOR', 'ROUND_HALF_DOWN', 'ROUND_HALF_EVEN', 'ROUND_HALF_UP', 'ROUND_UP', 'Rounded', 'Subnormal', 'Underflow', '_ContextManager', '_Infinity', '_Log10Memoize', '_NaN', '_NegativeInfinity', '_NegativeOne', '_One', '_SignedInfinity', '_WorkRep', '_Zero', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_all_zeros', '_condition_map', '_convert_other', '_copy', '_dec_from_triple', '_dexp', '_div_nearest', '_dlog', '_dlog10', '_dpower', '_exact_half', '_format_align', '_iexp', '_ilog', '_log10_digits', '_log10_lb', '_namedtuple', '_nbits', '_normalize', '_numbers', '_parse_format_specifier', '_parse_format_specifier_regex', '_parser', '_rshift_nearest', '_signals', '_sqrt_nearest', 'getcontext', 'localcontext', 'setcontext']

Das Moduls decimal ermöglicht Berechnungen mit hoher Genauigkeit.

1/7 mit verschiedenen Genauigkeiten

print(1.0/7.0) 0.142857142857
decimal.getcontext().prec = 20
a = decimal.Decimal(1)
b = decimal.Decimal(7)
c = a/b
print(c)
0.14285714285714285714
decimal.getcontext().prec = 50
a = decimal.Decimal(1)
b = decimal.Decimal(7)
c = a/b
print(c)
0.14285714285714285714285714285714285714285714285714

wurzel(2)

a = decimal.Decimal(2)
b =0.5
c = decimal.Decimal(str(b))
d = a**c
print(d)
1.4142135623730950488016887242096980785696718753769
print(decimal.Decimal(2).sqrt()) 1.4142135623730950488016887242096980785696718753769
print(d**2) 1.9999999999999999999999999999999999999999999999999

Berechnung von e über eine Reihenentwicklung

decimal.getcontext().prec = 100
a = decimal.Decimal(1)
b = decimal.Decimal(1)
for k in range(1, 70):
    b = b*k
    a = a + 1 / b
print(a)
2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166428
print(decimal.Decimal(1).exp()) 2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427
1.4142135623730950488016887242096980785696718753769


[zurück] [Inhaltsverzeichnis] [vor]