Real-time calculation of mean values with coroutines

--Coroutines are functions that can be stopped and restarted --Stop at yield --Send the value to the return value of yield and restart

average.py


#!/usr/bin/python                                                                                                                                                                                                  

def average():
    total = 0.0
    count = 0.0
    average = 0.0
    while True:
        #Coroutine points
        # -Generate average with yield and stop function
        # -When a value is received from send, it is assigned to value and the function restarts.
        value = yield average 
        total += value
        count += 1.0
        average = total/count

avg = average()
avg.next()
print avg.send(10.0)
print avg.send(20.0)
print avg.send(30.0)

--Result

10.0
15.0
20.0

Recommended Posts

Real-time calculation of mean values with coroutines
Sequential calculation of mean value with online algorithm
Error-free calculation with big.Float of golang
Calculation of mean IoU in object detection
1. Statistics learned with Python 1-3. Calculation of various statistics (statistics)
1. Statistics learned with Python 1-2. Calculation of various statistics (Numpy)
Aggregate VIP values of Smash Bros. with Pandas
Calculation of mutual information (continuous value) with numpy
Performs high-speed calculation of only specific descriptors with mordred
Find the sum of unique values with pandas crosstab
Maximum likelihood estimation of mean and variance with TensorFlow
[Python] Types of statistical values (features) and calculation methods
Real-time drawing with matplotlib
Numerical calculation with Python