Question about my loop

English = [90, 81, 73, 97, 85, 60, 74, 64, 72, 67, 87, 78, 85, 96, 77, 100, 92, 96]
Classical_Japanese = (71, 90, 79, 70, 67, 66, 60, 83, 57, 85, 93, 89, 78, 74, 65, 78, 53, 80)

def st_dev(x,y,z):
    return math.sqrt(sum((xi-y)**2 for xi in x) /(len(z)-1))

def st_dev2(x,y,z):
        sumsquares = 0
        x = 0
        n = len(z) -1 
        if n < 2:
            return "0"
        while x < n:
            sumsquares += (z[x]- y )**2
            x += 1
        
        variance = sumsquares/n
        return math.sqrt(variance)

The for loop vary 11.580917366893848 
meanwhile
the while loop vary 11.499076405082917

there is  big difference between this two what happen but if i remove minus one the results are the same for some reason
11.254628677422755
11.254628677422756

can you help me what happen to this?

2 comments · 75% upvoted · other discussions

comments

Adrewmc

For loops are basically just convenient while loops to the complier.

The reason you get different number is you’s obviously calculating different values

In

  sum(xi-y) **2 for xi in x)/(len(z)-1))

You always get every value in x

And

  while x < n: 
        print(x, end = “, “) 
        #code 

The while statement never adds the last variable. To prove this put this print statement.

Though you are dividing by the same number, you’re not dumping the same numerator.

Either_Back_1545 [OP]

Ohhh thats dope! thanks!