0

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?

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Notgrey
  • 19
  • 3
  • 1
    Would you also round up to 1.5 if it is between 1.35 and 1.5, or does 1.4999 round down to 1? – Erik McKelvey Feb 20 '22 at 06:11
  • Sorry, I didn't not include that vital bit of information. If it is > 1.46 then it rounds up to 1.5. If less then rounds down to 1 – Notgrey Feb 21 '22 at 03:10

2 Answers2

2

You could use this to round the number:

import math

def round_insulin(val):
    i = math.floor(val)
    decimal = val - i
    if decimal >= 0.85:
        return i + 1
    elif decimal >= 0.46:
        return i + 0.5
    else:
        return i
Erik McKelvey
  • 1,650
  • 1
  • 12
  • 23
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)
GabrielP
  • 777
  • 4
  • 8