Caffeine Half-Life Calculator

Track caffeine metabolism over time to see when it clears your system.

Average: 5–6 hours. Varies by individual (3–9h).

Часто задаваемые вопросы

Реализация кода

import math
from datetime import datetime, timedelta

HALF_LIFE_HOURS = 5  # average caffeine half-life

def caffeine_remaining(initial_mg, hours_elapsed, half_life=HALF_LIFE_HOURS):
    """Calculate remaining caffeine after elapsed time"""
    return initial_mg * (0.5 ** (hours_elapsed / half_life))

def hours_to_threshold(initial_mg, threshold_mg, half_life=HALF_LIFE_HOURS):
    """Calculate hours until caffeine falls below threshold"""
    if initial_mg <= threshold_mg:
        return 0
    return half_life * math.log2(initial_mg / threshold_mg)

# Example: 200mg caffeine consumed 3 hours ago
initial = 200
elapsed = 3
remaining = caffeine_remaining(initial, elapsed)
print(f"After {elapsed}h: {remaining:.1f}mg remaining")  # ~141.4mg

# Project forward
print("\nHourly breakdown:")
for h in range(0, 13, 2):
    mg = caffeine_remaining(remaining, h)
    print(f"+{h:2d}h: {mg:6.1f}mg")

# Time to sleep-safe level
h_to_50 = hours_to_threshold(remaining, 50)
print(f"\nFalls below 50mg in {h_to_50:.1f}h")

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.