'Is there a way to round an integer in a specific way with Python [duplicate]
I just started learning Python in school. I'm trying to write a program to do the simple calculation that determines my little sister’s insulin dosing (she just got diagnosed with Type 1 diabetes).
The equation looks like this:
(Current Blood Glucose - Target Blood Glucose) / her correction factor
Ex. She has a target of 120 and a correction factor of 80. When measured, the BG happens to be 260 so:
(260-120)/80 = 1.75 (which means 1.75 units of insulin)
Here's where I'm stuck - there's a diabetes safety thing where the answer is rounded down to the nearest .5 (in the above example this would mean 1.5 units). However, if the answer is >.85 then it is rounded up
Ex. 1.86 would be rounded to 2.00
I've tried several things but I'm either wrong in my syntax or it seems to grow into a really hard (long) way of doing this.
Does anyone know if there is a library/function to simplify this or have an idea about how to do this operation efficiently?
Solution 1:[1]
You could use the following function to do what you need.
# Function
def special_round(current, target, correction_f):
dosing = (current - target) / correction_f
print(f'Original dosing:\t{dosing}')
dosing_decimal = dosing % 1
dosing_int = dosing // 1
if (dosing_decimal > 0.85):
rounded_dosing = dosing_int + 1
elif (dosing_decimal>0.5):
rounded_dosing = dosing_int + 0.5
else:
rounded_dosing = dosing_int
print(f'Rounded dosing: \t{rounded_dosing}')
return rounded_dosing
# Implementation
rounded_dosing = special_round(current=260, target=120, correction_f=80)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | GabrielP |
