MrWallace
MrWallace

Reputation: 37

Wanting to convert cm^3 to L in python

I want to write a function that when I input the dimensions of a truncated cone (a cup) and an amount of liquid in litres returns how many of these cups can be filled up with the amount of liquid.I understand that 1L = 1000 cm^3 but I do not understand how I would incorporate it into my code to return the outcome I expect

def number_of_cups(bottom_radius, top_radius, height, litres_of_liquid):
    volume = math.pi / 3 * height * (bottom_radius**2 + top_radius * bottom_radius +  top_radius**2)


    return int(filled_cup)   

This is as far as I have got, I know I am close but I don't understand how to word my conversion,

Upvotes: 0

Views: 610

Answers (3)

Peter
Peter

Reputation: 553

That depends on the unit in which bottom_radius, top_radius and height are given. If we assume that those length are given in cm then

def number_of_cups(bottom_radius, top_radius, height, litres_of_liquid):
    volume = math.pi / 3 * height * (bottom_radius**2 + top_radius * bottom_radius +  top_radius**2)
    return int( litres_of_liquid * 1000 / volume )

litres_of_liquid * 1000 is litres converted to cm^3. The int() could be replaced by math.floor() in case the number of completely full cups is intended, math.ceil() will give the number of full or partially filled cups.

Finally, there is a nice package magnitude which encapsulates a physical quantity. You could use this package in case the user wants to specify different length units.

The Formula stated by the OP is correct.

Upvotes: 1

oz123
oz123

Reputation: 28868

Throwing my own anwer to the pile:

#!/usr/bin/python2
import math

# nothing about units here , but let's say it's cm
def cup_vol(b_rad=3, t_rad=4, h=5):  
    vol = math.pi/3 * (b_rad**2 + t_rad + b_rad + t_rad**2) * h
    return vol

def n_cups(liquid_amount, whole_cups=True):  # nothing about units here

    # liquid amount is Liter then first convert it to CM^3
    liquid_amount = liquid_amount*1000
    # this yields an int
    if whole_cups:
        return int(liquid_amount/cup_vol())
    # else, return a real number with fraction
    return liquid_amount/cup_vol() 


if __name__ == '__main__':
    print "4L fill %f cups" % n_cups(4)
    print "4L fill %f cups (real)" % n_cups(4, whole_cups=False)

Running the above script yields:

4L fill 23.000000 cups
4L fill 23.873241 cups (real)

Upvotes: 0

laike9m
laike9m

Reputation: 19368

OK, just want to point out, your volume calculation seems wrong.

def number_of_cups(bottom_radius, top_radius, height, litres_of_liquid):  
    volume = 4 * math.pi * height * (bottom_radius**2 + top_radius**2)/2  
    filled_cup = 1000 * litres_of_liquid / volume  
    return int(filled_cup)

And in case you did't know, division is different in Python2 and Python3.

Python 2

>>> 1/2
0

Python 3

>>> 1/2
0.5
>>> 1//2
0

Upvotes: 0

Related Questions