Between two values, and back from a probability

Normal questions go both ways: from values to a probability, and from a probability back to a value.

What to build

A program that finds a probability between two values and a percentile.

Requirements

  • Print between P: the probability that a value lies between a and b, to 4 decimal places.
  • Print percentile X: the value x with P(X ≤ x) = q, to 2 decimal places, found by bisection.

Input

One line: mean, sd, a, b and q.

Output

Two lines.

Constraints

sd is more than 0; a ≤ b; 0.001 ≤ q ≤ 0.999.

Example

Input:

100 15 85 115 0.5

Output:

between 0.6827
percentile 100.00

Why it works

The area between two values is the difference of two cumulative areas; and because the cumulative probability only grows with x, halving the interval always keeps the answer inside it.

Examples

Example 1 · Input
100 15 85 115 0.5
Expected output
between 0.6827
percentile 100.00
Example 2 · Input
0 1 -1.96 1.96 0.975
Expected output
between 0.9500
percentile 1.96

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

P(a ≤ X ≤ b) = P(X ≤ b) − P(X ≤ a).

Hint 2

For the percentile, halve an interval such as mean ± 10 sd until it is narrower than 0.000000001, keeping the half where P(X ≤ x) crosses q.

Solution

Show one correct solution (try it yourself first)
from math import erf, sqrt

mean, sd, a, b, q = map(float, input().split())


def below(x):
    return 0.5 * (1 + erf((x - mean) / sd / sqrt(2)))


print(f"between {below(b) - below(a):.4f}")
lo, hi = mean - 10 * sd, mean + 10 * sd
while hi - lo > 1e-9:
    mid = (lo + hi) / 2
    if below(mid) < q:
        lo = mid
    else:
        hi = mid
print(f"percentile {(lo + hi) / 2:.2f}")

Lesson: The normal distribution →