import random
import itertools

def test(number):
	return random.random()*number

Say I have a function and I want to repeat it x times so that I may calculate the standard deviation. How can I do this? I've tried using itertools.repeat(test(5),3) but it prints repeat(value,3) which I can't calculate the standard deviation. I feel like I am missing something really simple....
Any thoughts?
Thanks a bunch!

Dani AI

Generated

Short answer: you need to call the function N times and collect the independent results, then compute the standard deviation of that collection. The reason your original attempt didn’t work is that itertools.repeat will repeat the same object/value rather than invoking a callable each time (see the docs for itertools.repeat for details) — so you ended up with the same sample repeated instead of N independent samples.

is right that a simple loop or building a collection of results is the usual way; ’s generator idea is also a useful pattern when you want the function itself to yield many samples. For large N or streaming data, avoid materializing the whole list and use an online algorithm (Welford) to accumulate mean and variance in one pass:

def welford_std(values):
    n = 0
    mean = 0.0
    M2 = 0.0
    for x in values:
        n += 1
        delta = x - mean
        mean += delta / n
        M2 += delta * (x - mean)
    if n < 2:
        return float('nan')
    return (M2 / (n - 1)) ** 0.5

If you do collect samples, the std helpers in the stdlib are convenient: use statistics.stdev for the sample standard deviation or statistics.pstdev for population SD (documentation here). For reproducible runs, seed the RNG or use an independent random.Random instance. If performance matters, generate vectors with NumPy and use numpy.std (remember to set the degrees-of-freedom appropriately: ddof=1 for the sample sd).

A few quick checks when things look wrong: confirm you are calling the function each time (not repeating one evaluated result), make sure you have at least two samples before asking for sample SD, and beware of mutable return values being reused. References: itertools.repeat and statistics.stdev in the Python docs, and Welford’s algorithm (online variance) for streaming use.

Recommended Answers

All 2 Replies

Write a loop

for i in range(3):
    print test(5)

Or if you want to create a list of numbers

the_list = [ test(5) for i in range(3) ]

Also generator for loop would not be so bad as OP is considering itertools:

import random
def test(number):
    for count in range(number):
        yield random.random()

the_list = list(test(5))
print the_list
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.