Home > other >  How to divide a number a set of numbers that contains 0?
How to divide a number a set of numbers that contains 0?

Time:12-10

I am trying to assign a variable the values resulted by dividing other two, however, one of them divides by 0.

My variables are the following total_cost=[312198.0,230400.0,374345.0,367979.0,415502.0) alpha=[0.8181818181818182,0.6666666666666666,0.3076923076923077,0.6153846153846154,0.0]

And my desired output is to have cost_feasibility_efficiency=[381575.33,345949.94,1216621.24,597965.87,0]

My current code is

cost_feasibility_efficiency=[0.0,0.0,0.0,0.0,0.0]
for i in range(0,len(alpha)):
    cost_feasibility_efficiency[i]=total_cost[i]/alpha[i]
    
print(cost_feasibility_efficiency) 

The error I am getting is "float division by zero"

CodePudding user response:

Since dividing by zero is not allowed, we can just make sure our denominator alpha[i] isn't zero before we divide:

    cost_feasibility_efficiency=[0.0,0.0,0.0,0.0,0.0]
    for i in range(0,len(alpha)):
        if alpha[i] == 0:
            cost_feasibility_efficiency[i] = 0.0
        else:
            cost_feasibility_efficiency[i]=total_cost[i]/alpha[i]

    print(cost_feasibility_efficiency) 

You can choose what happens if we run into a divide-by-zero. In the above case it just sets the result to 0.0.

CodePudding user response:

You can use try/except to catch an exception:

cost_feasibility_efficiency=[0.0,0.0,0.0,0.0,0.0]
for i in range(0,len(alpha)):
    try:
        cost_feasibility_efficiency[i] = total_cost[i] / alpha[i]
    except ZeroDivisionError:
        cost_feasibility_efficiency[i] = 0.0

print(cost_feasibility_efficiency)
  • Related