Module 4 · Location, Ranking, and Exploratory Summaries Lesson 36 of 120
Percentiles, Quantiles, and Quartiles
A percentile is incomplete without its interpolation rule.
Transcript
20 sentences · select one to jump thereCheck your understanding
Was five hours observed in the sample?
Code lab
Run it yourself
The lesson source in 7 languages. Edit it, run TypeScript and Python right here, and compare with the expected output.
/**
* Fintech Math Bootcamp · Lesson 036 of 120
* Percentiles, Quantiles, and Quartiles
* Module 04: Location, Ranking, and Exploratory Summaries
*
* Scenario: A percentile is incomplete without its interpolation rule
* Rule: type 7: h=(n−1)p, interpolate adjacent values
*
* Try it: Was five hours observed in the sample?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/location-ranking-and-exploratory-summaries/percentiles-quantiles-and-quartiles/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*/
export function lesson036() {
const x = [1, 2, 2, 4, 9].sort((a,b) => a-b);
const q = (p: number) => { // type-7 linear interpolation
const h = (x.length-1)*p, i = Math.floor(h);
return x[i] + (h-i)*(x[Math.min(i+1,x.length-1)]-x[i]);
};
const result = {q25:q(.25), q50:q(.5), q75:q(.75), q80:q(.8)};
return result;
}
export const checkedResult = {"q25":2,"q50":2,"q75":4,"q80":5.000000000000001};
// Run this file directly: npx tsx lessons/04-location-ranking-and-exploratory-summaries/036-percentiles-quantiles-and-quartiles.ts
if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop()!)) {
console.log(JSON.stringify(lesson036(), null, 2));
}
Your output
Press Run to execute the code in your browser.
Expected output
{
"q25": 2,
"q50": 2,
"q75": 4,
"q80": 5.000000000000001
}# Fintech Math Bootcamp · Lesson 036 of 120
# Percentiles, Quantiles, and Quartiles
# Module 04: Location, Ranking, and Exploratory Summaries
#
# Scenario: A percentile is incomplete without its interpolation rule
# Rule: type 7: h=(n−1)p, interpolate adjacent values
#
# Try it: Was five hours observed in the sample?
#
# Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/location-ranking-and-exploratory-summaries/percentiles-quantiles-and-quartiles/
# Free course: https://courses.thefintechbuilder.com
# Synthetic teaching example, not financial advice or a production library.
import json
import math
def lesson036() -> dict:
x = sorted([1, 2, 2, 4, 9])
def q(p: float) -> float: # type-7 linear interpolation
h = (len(x) - 1) * p
i = math.floor(h)
return x[i] + (h - i) * (x[min(i + 1, len(x) - 1)] - x[i])
return {"q25": q(0.25), "q50": q(0.5), "q75": q(0.75), "q80": q(0.8)}
if __name__ == "__main__":
print(json.dumps(lesson036(), indent=2))
Your output
Press Run to execute the code in your browser.
Expected output
{
"q25": 2,
"q50": 2,
"q75": 4,
"q80": 5.000000000000001
}/**
* Fintech Math Bootcamp · Lesson 036 of 120
* Percentiles, Quantiles, and Quartiles
* Module 04: Location, Ranking, and Exploratory Summaries
*
* Scenario: A percentile is incomplete without its interpolation rule
* Rule: type 7: h=(n−1)p, interpolate adjacent values
*
* Try it: Was five hours observed in the sample?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/location-ranking-and-exploratory-summaries/percentiles-quantiles-and-quartiles/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Main {
// Type-7 linear interpolation between adjacent order statistics; x must be sorted.
static double quantile7(double[] x, double p) {
double h = (x.length - 1) * p;
int i = (int) Math.floor(h);
return x[i] + (h - i) * (x[Math.min(i + 1, x.length - 1)] - x[i]);
}
static Map<String, Object> lesson036() {
double[] x = {1, 2, 2, 4, 9};
Arrays.sort(x);
Map<String, Object> result = new LinkedHashMap<String, Object>();
result.put("q25", quantile7(x, 0.25));
result.put("q50", quantile7(x, 0.5));
result.put("q75", quantile7(x, 0.75));
result.put("q80", quantile7(x, 0.8));
return result;
}
public static void main(String[] args) {
System.out.println(toJson(lesson036(), ""));
}
// --- Minimal JSON printer: maps keep insertion order, 2-space indent. ---
static String toJson(Object value, String indent) {
if (value == null) return "null";
if (value instanceof String) return "\"" + value + "\"";
if (value instanceof Double) return formatNumber((Double) value);
if (value instanceof Number) return value.toString();
if (value instanceof double[]) {
List<Object> items = new ArrayList<Object>();
for (double v : (double[]) value) items.add(v);
return toJson(items, indent);
}
String inner = indent + " ";
StringBuilder sb = new StringBuilder();
if (value instanceof Map) {
Map<?, ?> map = (Map<?, ?>) value;
if (map.isEmpty()) return "{}";
sb.append("{\n");
int i = 0;
for (Map.Entry<?, ?> entry : map.entrySet()) {
sb.append(inner).append('"').append(entry.getKey()).append("\": ")
.append(toJson(entry.getValue(), inner))
.append(++i < map.size() ? ",\n" : "\n");
}
return sb.append(indent).append('}').toString();
}
List<?> list = (List<?>) value;
if (list.isEmpty()) return "[]";
sb.append("[\n");
for (int i = 0; i < list.size(); i++) {
sb.append(inner).append(toJson(list.get(i), inner))
.append(i + 1 < list.size() ? ",\n" : "\n");
}
return sb.append(indent).append(']').toString();
}
static String formatNumber(double v) {
if (Double.isNaN(v) || Double.isInfinite(v)) return "null";
if (v == Math.rint(v) && Math.abs(v) < 1e15) return Long.toString((long) v);
return Double.toString(v);
}
}
No browser runner for Java yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"q25": 2,
"q50": 2,
"q75": 4,
"q80": 5.000000000000001
}// Fintech Math Bootcamp · Lesson 036 of 120
// Percentiles, Quantiles, and Quartiles
// Module 04: Location, Ranking, and Exploratory Summaries
//
// Scenario: A percentile is incomplete without its interpolation rule
// Rule: type 7: h=(n−1)p, interpolate adjacent values
//
// Try it: Was five hours observed in the sample?
//
// Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/location-ranking-and-exploratory-summaries/percentiles-quantiles-and-quartiles/
// Free course: https://courses.thefintechbuilder.com
// Synthetic teaching example, not financial advice or a production library.
package main
import (
"encoding/json"
"fmt"
"math"
"sort"
)
// Quantiles holds type-7 quantiles at four probabilities.
type Quantiles struct {
Q25 float64 `json:"q25"`
Q50 float64 `json:"q50"`
Q75 float64 `json:"q75"`
Q80 float64 `json:"q80"`
}
// quantile7 interpolates linearly between adjacent order statistics (type 7).
func quantile7(x []float64, p float64) float64 {
h := float64(len(x)-1) * p
i := int(math.Floor(h))
return x[i] + (h-float64(i))*(x[min(i+1, len(x)-1)]-x[i])
}
func lesson036() Quantiles {
x := []float64{1, 2, 2, 4, 9}
sort.Float64s(x)
return Quantiles{
Q25: quantile7(x, 0.25),
Q50: quantile7(x, 0.5),
Q75: quantile7(x, 0.75),
Q80: quantile7(x, 0.8),
}
}
func main() {
out, _ := json.MarshalIndent(lesson036(), "", " ")
fmt.Println(string(out))
}
No browser runner for Go yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"q25": 2,
"q50": 2,
"q75": 4,
"q80": 5.000000000000001
}/**
* Fintech Math Bootcamp · Lesson 036 of 120
* Percentiles, Quantiles, and Quartiles
* Module 04: Location, Ranking, and Exploratory Summaries
*
* Scenario: A percentile is incomplete without its interpolation rule
* Rule: type 7: h=(n−1)p, interpolate adjacent values
*
* Try it: Was five hours observed in the sample?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/location-ranking-and-exploratory-summaries/percentiles-quantiles-and-quartiles/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*/
#include <algorithm>
#include <charconv>
#include <cmath>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
// --- Minimal JSON value and printer: objects keep insertion order, 2-space indent. ---
struct Json {
enum class Kind { Null, Number, Text, Array, Object };
Kind kind = Kind::Null;
double number = 0;
std::string text;
std::vector<std::string> keys; // object keys, parallel to items
std::vector<Json> items; // array elements or object values
};
Json num(double v) { Json j; j.kind = Json::Kind::Number; j.number = v; return j; }
Json str(const std::string& s) { Json j; j.kind = Json::Kind::Text; j.text = s; return j; }
Json arr(const std::vector<Json>& values) { Json j; j.kind = Json::Kind::Array; j.items = values; return j; }
Json arr(const std::vector<double>& values) {
std::vector<Json> items;
for (double v : values) items.push_back(num(v));
return arr(items);
}
Json obj(const std::vector<std::pair<std::string, Json>>& fields) {
Json j;
j.kind = Json::Kind::Object;
for (const auto& [key, value] : fields) { j.keys.push_back(key); j.items.push_back(value); }
return j;
}
std::string formatNumber(double v) {
if (!std::isfinite(v)) return "null";
char buf[64];
auto end = std::to_chars(buf, buf + sizeof buf, v).ptr; // shortest round-trip form
return std::string(buf, end);
}
void writeJson(std::ostream& out, const Json& j, const std::string& indent) {
switch (j.kind) {
case Json::Kind::Null: out << "null"; return;
case Json::Kind::Number: out << formatNumber(j.number); return;
case Json::Kind::Text: out << '"' << j.text << '"'; return;
default: break;
}
bool isObject = j.kind == Json::Kind::Object;
if (j.items.empty()) { out << (isObject ? "{}" : "[]"); return; }
std::string inner = indent + " ";
out << (isObject ? "{\n" : "[\n");
for (size_t i = 0; i < j.items.size(); ++i) {
out << inner;
if (isObject) out << '"' << j.keys[i] << "\": ";
writeJson(out, j.items[i], inner);
out << (i + 1 < j.items.size() ? ",\n" : "\n");
}
out << indent << (isObject ? '}' : ']');
}
// --- Lesson ---
// Type-7 linear interpolation between adjacent order statistics; x must be sorted.
double quantile7(const std::vector<double>& x, double p) {
double h = (x.size() - 1) * p;
size_t i = static_cast<size_t>(std::floor(h));
return x[i] + (h - i) * (x[std::min(i + 1, x.size() - 1)] - x[i]);
}
Json lesson036() {
std::vector<double> x = {1, 2, 2, 4, 9};
std::sort(x.begin(), x.end());
return obj({
{"q25", num(quantile7(x, 0.25))},
{"q50", num(quantile7(x, 0.5))},
{"q75", num(quantile7(x, 0.75))},
{"q80", num(quantile7(x, 0.8))},
});
}
int main() {
writeJson(std::cout, lesson036(), "");
std::cout << '\n';
}
No browser runner for C++ yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"q25": 2,
"q50": 2,
"q75": 4,
"q80": 5.000000000000001
}// Fintech Math Bootcamp · Lesson 036 of 120
// Percentiles, Quantiles, and Quartiles
// Module 04: Location, Ranking, and Exploratory Summaries
//
// Scenario: A percentile is incomplete without its interpolation rule
// Rule: type 7: h=(n−1)p, interpolate adjacent values
//
// Try it: Was five hours observed in the sample?
//
// Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/location-ranking-and-exploratory-summaries/percentiles-quantiles-and-quartiles/
// Free course: https://courses.thefintechbuilder.com
// Synthetic teaching example, not financial advice or a production library.
// --- Minimal JSON value and printer: objects keep insertion order, 2-space indent. ---
#[allow(dead_code)]
enum Json {
Null,
Num(f64),
Str(String),
Arr(Vec<Json>),
Obj(Vec<(String, Json)>),
}
#[allow(dead_code)]
fn nums(values: &[f64]) -> Json {
Json::Arr(values.iter().map(|&v| Json::Num(v)).collect())
}
#[allow(dead_code)]
fn obj(fields: Vec<(&str, Json)>) -> Json {
Json::Obj(fields.into_iter().map(|(k, v)| (k.to_string(), v)).collect())
}
fn format_number(v: f64) -> String {
if !v.is_finite() {
return "null".to_string();
}
if v.fract() == 0.0 && v.abs() < 1e15 {
return format!("{}", v as i64);
}
format!("{:?}", v) // shortest round-trip form
}
impl Json {
fn render(&self, indent: &str) -> String {
let inner = format!("{} ", indent);
match self {
Json::Null => "null".to_string(),
Json::Num(v) => format_number(*v),
Json::Str(s) => format!("\"{}\"", s),
Json::Arr(items) if items.is_empty() => "[]".to_string(),
Json::Obj(fields) if fields.is_empty() => "{}".to_string(),
Json::Arr(items) => {
let lines: Vec<String> = items.iter().map(|v| format!("{}{}", inner, v.render(&inner))).collect();
format!("[\n{}\n{}]", lines.join(",\n"), indent)
}
Json::Obj(fields) => {
let lines: Vec<String> = fields
.iter()
.map(|(k, v)| format!("{}\"{}\": {}", inner, k, v.render(&inner)))
.collect();
format!("{{\n{}\n{}}}", lines.join(",\n"), indent)
}
}
}
}
// --- Lesson ---
/// Type-7 linear interpolation between adjacent order statistics; `x` must be sorted.
fn quantile7(x: &[f64], p: f64) -> f64 {
let h = (x.len() - 1) as f64 * p;
let i = h.floor() as usize;
x[i] + (h - i as f64) * (x[(i + 1).min(x.len() - 1)] - x[i])
}
fn lesson036() -> Json {
let mut x: Vec<f64> = vec![1.0, 2.0, 2.0, 4.0, 9.0];
x.sort_by(|a, b| a.partial_cmp(b).unwrap());
obj(vec![
("q25", Json::Num(quantile7(&x, 0.25))),
("q50", Json::Num(quantile7(&x, 0.5))),
("q75", Json::Num(quantile7(&x, 0.75))),
("q80", Json::Num(quantile7(&x, 0.8))),
])
}
fn main() {
println!("{}", lesson036().render(""));
}
No browser runner for Rust yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"q25": 2,
"q50": 2,
"q75": 4,
"q80": 5.000000000000001
}/**
* Fintech Math Bootcamp · Lesson 036 of 120
* Percentiles, Quantiles, and Quartiles
* Module 04: Location, Ranking, and Exploratory Summaries
*
* Scenario: A percentile is incomplete without its interpolation rule
* Rule: type 7: h=(n−1)p, interpolate adjacent values
*
* Try it: Was five hours observed in the sample?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/location-ranking-and-exploratory-summaries/percentiles-quantiles-and-quartiles/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*/
using System;
using System.Linq;
using System.Text.Json;
var options = new JsonSerializerOptions { WriteIndented = true };
Console.WriteLine(JsonSerializer.Serialize(Lesson036(), options));
static object Lesson036()
{
double[] x = new double[] { 1, 2, 2, 4, 9 }.OrderBy(v => v).ToArray();
// Type-7 linear interpolation between adjacent order statistics.
double Q(double p)
{
double h = (x.Length - 1) * p;
int i = (int)Math.Floor(h);
return x[i] + (h - i) * (x[Math.Min(i + 1, x.Length - 1)] - x[i]);
}
return new { q25 = Q(0.25), q50 = Q(0.5), q75 = Q(0.75), q80 = Q(0.8) };
}
No browser runner for C# yet
Read the code here, then run it in your own toolchain or a ready-made cloud workspace.
Expected output
{
"q25": 2,
"q50": 2,
"q75": 4,
"q80": 5.000000000000001
}Prefer your own machine? Every file is in the course repository · open it in Codespaces.
Lesson notes
The rule
type 7: h=(n−1)p, interpolate adjacent values