Skip to content

Commit c0b0b12

Browse files
kavienanjCaedenPHcclauss
authored
Add Ideal Gas Law for physics (TheAlgorithms#6503)
* add physics ideal gas law * run pre commit * Update physics/ideal_gas_law.py Suggestion #1 Co-authored-by: Caeden <[email protected]> * Update physics/ideal_gas_law.py Suggestion #2 Co-authored-by: Caeden <[email protected]> * run pre commit * Update volume return line sugesstion Co-authored-by: Caeden Perelli-Harris <[email protected]> * Add suggestions * Apply suggestions from code review Co-authored-by: Caeden Perelli-Harris <[email protected]> Co-authored-by: Caeden <[email protected]> Co-authored-by: Christian Clauss <[email protected]>
1 parent ca92338 commit c0b0b12

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

physics/ideal_gas_law.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
The ideal gas law, also called the general gas equation, is the
3+
equation of state of a hypothetical ideal gas. It is a good approximation
4+
of the behavior of many gases under many conditions, although it has
5+
several limitations. It was first stated by Benoît Paul Émile Clapeyron
6+
in 1834 as a combination of the empirical Boyle's law, Charles's law,
7+
Avogadro's law, and Gay-Lussac's law.[1] The ideal gas law is often written
8+
in an empirical form:
9+
------------
10+
| PV = nRT |
11+
------------
12+
P = Pressure (Pa)
13+
V = Volume (m^3)
14+
n = Amount of substance (mol)
15+
R = Universal gas constant
16+
T = Absolute temperature (Kelvin)
17+
18+
(Description adapted from https://en.wikipedia.org/wiki/Ideal_gas_law )
19+
"""
20+
21+
UNIVERSAL_GAS_CONSTANT = 8.314462 # Unit - J mol-1 K-1
22+
23+
24+
def pressure_of_gas_system(moles: float, kelvin: float, volume: float) -> float:
25+
"""
26+
>>> pressure_of_gas_system(2, 100, 5)
27+
332.57848
28+
>>> pressure_of_gas_system(0.5, 273, 0.004)
29+
283731.01575
30+
>>> pressure_of_gas_system(3, -0.46, 23.5)
31+
Traceback (most recent call last):
32+
...
33+
ValueError: Invalid inputs. Enter positive value.
34+
"""
35+
if moles < 0 or kelvin < 0 or volume < 0:
36+
raise ValueError("Invalid inputs. Enter positive value.")
37+
return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume
38+
39+
40+
def volume_of_gas_system(moles: float, kelvin: float, pressure: float) -> float:
41+
"""
42+
>>> volume_of_gas_system(2, 100, 5)
43+
332.57848
44+
>>> volume_of_gas_system(0.5, 273, 0.004)
45+
283731.01575
46+
>>> volume_of_gas_system(3, -0.46, 23.5)
47+
Traceback (most recent call last):
48+
...
49+
ValueError: Invalid inputs. Enter positive value.
50+
"""
51+
if moles < 0 or kelvin < 0 or pressure < 0:
52+
raise ValueError("Invalid inputs. Enter positive value.")
53+
return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure
54+
55+
56+
if __name__ == "__main__":
57+
from doctest import testmod
58+
59+
testmod()

0 commit comments

Comments
 (0)