From f995662f05be2d468c72571a52fddef8508bb299 Mon Sep 17 00:00:00 2001 From: Donkie Date: Mon, 10 Jul 2023 11:02:22 +0200 Subject: [PATCH] Conversion math library update * Now inputs diameter instead of radius to prevent confusion * Added length_from_weight --- spoolman/database/spool.py | 2 +- spoolman/math.py | 22 +++++++++++++++++++--- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/spoolman/database/spool.py b/spoolman/database/spool.py index d1e7c56..e591bd6 100644 --- a/spoolman/database/spool.py +++ b/spoolman/database/spool.py @@ -213,7 +213,7 @@ async def use_length(db: AsyncSession, spool_id: int, length: float) -> models.S # Calculate and use weight weight = weight_from_length( length=length, - radius=filament_info[0] / 2, + diameter=filament_info[0], density=filament_info[1], ) await use_weight_safe(db, spool_id, weight) diff --git a/spoolman/math.py b/spoolman/math.py index 87a7719..a7940b8 100644 --- a/spoolman/math.py +++ b/spoolman/math.py @@ -3,17 +3,33 @@ import math -def weight_from_length(*, length: float, radius: float, density: float) -> float: +def weight_from_length(*, length: float, diameter: float, density: float) -> float: """Calculate the weight of a piece of filament. Args: length (float): Filament length in mm - radius (float): Filament radius in mm + diameter (float): Filament diameter in mm density (float): Density of filament material in g/cm3 Returns: float: Weight in g """ - volume_mm3 = length * math.pi * radius * radius + volume_mm3 = length * math.pi * (diameter / 2) ** 2 volume_cm3 = volume_mm3 / 1000 return density * volume_cm3 + + +def length_from_weight(*, weight: float, diameter: float, density: float) -> float: + """Calculate the length of a piece of filament. + + Args: + weight (float): Filament weight in g + diameter (float): Filament diameter in mm + density (float): Density of filament material in g/cm3 + + Returns: + float: Length in mm + """ + volume_cm3 = weight / density + volume_mm3 = volume_cm3 * 1000 + return volume_mm3 / (math.pi * (diameter / 2) ** 2)