Dies ist die Support Website des Buches:
Das Python Praxisbuch
Der große Profi-Leitfaden für Programmierer
Farid Hajji
Addison Wesley / Pearson Education
ISBN 978-3-8273-2543-3 (Sep 2008), 1298 Seiten.
4. Zahlen¶
Dezimalzahlen mit dem decimal-Modul¶
Screenshots:
#!/usr/bin/env python
# decimal_localcontext.py -- compute with specific precision
from __future__ import with_statement
import decimal
def sumprec(prec=6, arglist=[]):
"Compute the sum of list arglist with precision prec."
with decimal.localcontext() as lctx:
# Here, computations should occur with precision prec
lctx.prec = prec
result = decimal.Decimal("0")
for num in arglist:
result = result + decimal.Decimal(num)
# Resume computation with default or previous precision
return result
if __name__ == '__main__':
import sys
if len(sys.argv) < 2:
print "Usage:", sys.argv[0], "precision [num1 [num2 ...]]"
sys.exit(1)
print sumprec(int(sys.argv[1]), sys.argv[2:])
Zufallszahlen mit dem random-Modul¶
Zufallszahlen mit dem Mersenne Twister¶
#!/usr/bin/env python
# get_sample_naive.py -- Get a random sample from a population. Naive version.
import random
def get_sample_naive(population, size):
"Return a list of size random elements from the list population."
population_size = len(population)
result = []
i = 0
while (i < size):
idx = random.randrange(0, population_size)
result.append(population[idx])
i = i + 1
return result
if __name__ == '__main__':
print get_sample_naive(['apples', 'oranges', 'lemons', 'bananas'], 3)
Zufallszahlen aus einer Entropiequelle¶
Manpages: