Halaman

Senin, 17 Maret 2025

Python - Statistik - Mean, Median, Modus - data tunggal

import random


#random data -------------------------------

mydata = [[10,1],[20,1],[30,1],[40,1],[50,1],[60,1],[70,1],[80,1],[90,1],[100,1]]

frek = [1,2,3,4,5,5,6,7,8,9]

nn = len(frek)


def acakfrek(_frek):

    nn = int(len(_frek))

    for i in range(nn):

        m = random.randint(0, nn-1)

        n = random.randint(0, nn-1)

        temp = _frek[m]

        _frek[m] = _frek[n]

        _frek[n] = temp

    return _frek  

frek = acakfrek(frek)


#mengisi data khusus frekuensi

def isiDataf(_data, _frek):

    _mydata = _data

    for i in range(nn):

        _mydata[i][1] = frek[i]



#mencari total frekuensi

def totf(arr):

    totalf = 0

    for i in range(len(arr)):

        totalf += arr[i]

    return totalf

    


#mean ------------------------------------

def meanf(arr,totf):

    totnil = 0

    for i in range(len(arr)):

        totnil += arr[i][0]*arr[i][1]

    _mean = totnil/totf 

    return _mean



#median ----------------------------------

def fkumulatif(arr):

    ffk = []

    for i in range(len(arr)):

        tfk = 0

        for j in range(i+1):

            tfk+=arr[j]

        ffk.append(tfk)

    return ffk


def medianf(arrdata,totf):

    a1 = 0

    a2 = 0

    cektotal = totf%2

    if cektotal==0 :

        #ada2

        a1 = int(totf/2)

        a2 = a1+1 

    else :

        #ada1

        a1 = int((totf+1)/2)

        a2 = a1

    med1=0

    med2=0

    i=0

    while a1>fk[i] :

        i+=1

    med1 = i

    i=0

    while a2>fk[i] :

        i+=1

    med2 = i

    _median = (1/2)*(arrdata[med1][0]+arrdata[med2][0])

    return _median



#modus ------------------------------------

def modusf(arrdata):

    _modus = arrdata[0][0]

    fmodus = arrdata[0][1]

    for i in range(nn):

        if fmodus<arrdata[i][1]:

            fmodus = arrdata[i][1]

            _modus = arrdata[i][0]

    return _modus

 

 

isiDataf(mydata, frek)

totalfrek = totf(frek)

fk = fkumulatif(frek)

mean = meanf(mydata,totalfrek)

median = medianf(mydata, totalfrek)

modus = modusf(mydata)

print("mydata     = ",mydata)

print("totalfrek  = ",totalfrek)

print("fkumulatif = ",fk)

print("Mean       = ",mean)

print("Median     = ",median)    

print("Modus      = ",modus)




Tidak ada komentar:

Posting Komentar