Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading