Probability Calculator

Calculate single event, compound (AND/OR), conditional, and at-least-one probabilities.

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

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

from fractions import Fraction
import math

def single_event_probability(favorable: int, total: int) -> dict:
    """P(A) = favorable / total"""
    if total <= 0:
        raise ValueError("Total outcomes must be positive")
    prob = favorable / total
    frac = Fraction(favorable, total)
    return {
        "decimal": round(prob, 6),
        "fraction": f"{frac.numerator}/{frac.denominator}",
        "percentage": round(prob * 100, 4),
    }

def compound_and_probability(p_a: float, p_b: float) -> float:
    """P(A and B) = P(A) × P(B) for independent events"""
    return p_a * p_b

def compound_or_probability(p_a: float, p_b: float) -> float:
    """P(A or B) = P(A) + P(B) - P(A and B) for independent events"""
    return p_a + p_b - p_a * p_b

def at_least_one_probability(p_single: float, trials: int) -> float:
    """P(at least one) = 1 - P(none) = 1 - (1-p)^n"""
    return 1 - (1 - p_single) ** trials

# Examples
print("=== Single Event ===")
r = single_event_probability(3, 6)  # Rolling a 1, 2, or 3
print(f"P = {r['fraction']} = {r['decimal']} = {r['percentage']}%")

print("\n=== Compound (AND) ===")
p_and = compound_and_probability(1/6, 1/6)  # Two dice both show 1
print(f"P(1 and 1) = {p_and:.6f} = {p_and*100:.4f}%")

print("\n=== Compound (OR) ===")
p_or = compound_or_probability(0.5, 0.3)
print(f"P(A or B) = {p_or:.6f} = {p_or*100:.2f}%")

print("\n=== At Least One ===")
p_atleast = at_least_one_probability(1/6, 3)  # At least one 6 in 3 rolls
print(f"P(at least one 6 in 3 rolls) = {p_atleast:.6f} = {p_atleast*100:.2f}%")

Comments & Feedback

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