Module 1 · Mathematical Language and Quantitative Reasoning Lesson 7 of 120
Linear Equations and Systems
Reconciling transaction counts and fee totals.
Transcript
27 sentences · select one to jump thereCheck your understanding
What if both equations are identical?
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 007 of 120
* Linear Equations and Systems
* Module 01: Mathematical Language and Quantitative Reasoning
*
* Scenario: Reconciling transaction counts and fee totals
* Rule: x + y = 10; 2x + 3y = 26
*
* Try it: What if both equations are identical?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/mathematical-language-and-quantitative-reasoning/linear-equations-and-systems/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*/
export function lesson007() {
const lowFee = 2, highFee = 3, totalCount = 10, totalFees = 26;
const det = highFee - lowFee; // determinant of [[1, 1], [lowFee, highFee]]
if (det === 0) throw new Error("Equations are not independent");
const highFeeCount = (totalFees - lowFee * totalCount) / det;
const lowFeeCount = totalCount - highFeeCount;
if (lowFee * lowFeeCount + highFee * highFeeCount !== totalFees)
throw new Error("Solution fails verification");
const result = {lowFeeCount, highFeeCount};
return result;
}
export const checkedResult = {"lowFeeCount":4,"highFeeCount":6};
// Run this file directly: npx tsx lessons/01-mathematical-language-and-quantitative-reasoning/007-linear-equations-and-systems.ts
if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop()!)) {
console.log(JSON.stringify(lesson007(), null, 2));
}
Your output
Press Run to execute the code in your browser.
Expected output
{
"lowFeeCount": 4,
"highFeeCount": 6
}"""
Fintech Math Bootcamp · Lesson 007 of 120
Linear Equations and Systems
Module 01: Mathematical Language and Quantitative Reasoning
Scenario: Reconciling transaction counts and fee totals
Rule: x + y = 10; 2x + 3y = 26
Try it: What if both equations are identical?
Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/mathematical-language-and-quantitative-reasoning/linear-equations-and-systems/
Free course: https://courses.thefintechbuilder.com
Synthetic teaching example, not financial advice or a production library.
Run it: python main.py
"""
import json
def lesson007() -> dict:
low_fee, high_fee, total_count, total_fees = 2, 3, 10, 26
det = high_fee - low_fee # determinant of [[1, 1], [low_fee, high_fee]]
if det == 0:
raise ValueError("Equations are not independent")
high_fee_count = (total_fees - low_fee * total_count) / det
low_fee_count = total_count - high_fee_count
if low_fee * low_fee_count + high_fee * high_fee_count != total_fees:
raise ValueError("Solution fails verification")
result = {"lowFeeCount": low_fee_count, "highFeeCount": high_fee_count}
return result
if __name__ == "__main__":
print(json.dumps(lesson007(), indent=2))
Your output
Press Run to execute the code in your browser.
Expected output
{
"lowFeeCount": 4,
"highFeeCount": 6
}/**
* Fintech Math Bootcamp · Lesson 007 of 120
* Linear Equations and Systems
* Module 01: Mathematical Language and Quantitative Reasoning
*
* Scenario: Reconciling transaction counts and fee totals
* Rule: x + y = 10; 2x + 3y = 26
*
* Try it: What if both equations are identical?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/mathematical-language-and-quantitative-reasoning/linear-equations-and-systems/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*
* Run it: javac Main.java && java Main
*/
public class Main {
static final class FeeCounts {
final double lowFeeCount;
final double highFeeCount;
FeeCounts(double lowFeeCount, double highFeeCount) {
this.lowFeeCount = lowFeeCount;
this.highFeeCount = highFeeCount;
}
}
static FeeCounts lesson007() {
double lowFee = 2, highFee = 3, totalCount = 10, totalFees = 26;
double det = highFee - lowFee; // determinant of [[1, 1], [lowFee, highFee]]
if (det == 0) throw new IllegalStateException("Equations are not independent");
double highFeeCount = (totalFees - lowFee * totalCount) / det;
double lowFeeCount = totalCount - highFeeCount;
if (lowFee * lowFeeCount + highFee * highFeeCount != totalFees)
throw new IllegalStateException("Solution fails verification");
FeeCounts result = new FeeCounts(lowFeeCount, highFeeCount);
return result;
}
public static void main(String[] args) {
FeeCounts result = lesson007();
System.out.println(object(
"lowFeeCount", num(result.lowFeeCount),
"highFeeCount", num(result.highFeeCount)));
}
// Formats a double the way JSON.stringify does: whole numbers without ".0", null for NaN or infinity.
static String num(double x) {
if (Double.isNaN(x) || Double.isInfinite(x)) return "null";
if (x == Math.rint(x) && Math.abs(x) < 1e15) return String.valueOf((long) x);
return String.valueOf(x);
}
static String quote(String text) {
return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\"";
}
// Indents an already formatted JSON value by one level.
static String nested(String json) {
return json.replace("\n", "\n ");
}
static String object(String... keysAndValues) {
if (keysAndValues.length == 0) return "{}";
StringBuilder out = new StringBuilder("{");
for (int i = 0; i < keysAndValues.length; i += 2) {
out.append(i == 0 ? "\n " : ",\n ")
.append(quote(keysAndValues[i])).append(": ").append(nested(keysAndValues[i + 1]));
}
return out.append("\n}").toString();
}
}
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
{
"lowFeeCount": 4,
"highFeeCount": 6
}// Fintech Math Bootcamp · Lesson 007 of 120
// Linear Equations and Systems
// Module 01: Mathematical Language and Quantitative Reasoning
//
// Scenario: Reconciling transaction counts and fee totals
// Rule: x + y = 10; 2x + 3y = 26
//
// Try it: What if both equations are identical?
//
// Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/mathematical-language-and-quantitative-reasoning/linear-equations-and-systems/
// Free course: https://courses.thefintechbuilder.com
// Synthetic teaching example, not financial advice or a production library.
//
// Run it: go run main.go
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
)
type FeeCounts struct {
LowFeeCount float64 `json:"lowFeeCount"`
HighFeeCount float64 `json:"highFeeCount"`
}
func lesson007() (FeeCounts, error) {
lowFee, highFee, totalCount, totalFees := 2.0, 3.0, 10.0, 26.0
det := highFee - lowFee // determinant of [[1, 1], [lowFee, highFee]]
if det == 0 {
return FeeCounts{}, errors.New("Equations are not independent")
}
highFeeCount := (totalFees - lowFee*totalCount) / det
lowFeeCount := totalCount - highFeeCount
if lowFee*lowFeeCount+highFee*highFeeCount != totalFees {
return FeeCounts{}, errors.New("Solution fails verification")
}
result := FeeCounts{LowFeeCount: lowFeeCount, HighFeeCount: highFeeCount}
return result, nil
}
func main() {
result, err := lesson007()
if err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
printJSON(result)
}
// printJSON prints a value as JSON indented with two spaces, like JSON.stringify(value, null, 2).
func printJSON(value any) {
out, err := json.MarshalIndent(value, "", " ")
if err != nil {
panic(err)
}
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
{
"lowFeeCount": 4,
"highFeeCount": 6
}/**
* Fintech Math Bootcamp · Lesson 007 of 120
* Linear Equations and Systems
* Module 01: Mathematical Language and Quantitative Reasoning
*
* Scenario: Reconciling transaction counts and fee totals
* Rule: x + y = 10; 2x + 3y = 26
*
* Try it: What if both equations are identical?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/mathematical-language-and-quantitative-reasoning/linear-equations-and-systems/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*
* Run it: g++ -std=c++17 -o main main.cpp && ./main
*/
#include <charconv>
#include <cmath>
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
// Formats a double the way JSON.stringify does: shortest round-trip form, null for NaN or infinity.
std::string num(double x) {
if (!std::isfinite(x)) return "null";
char buffer[32];
auto [end, error] = std::to_chars(buffer, buffer + sizeof buffer, x);
(void)error;
return std::string(buffer, end);
}
std::string quote(const std::string& text) {
std::string out = "\"";
for (char c : text) {
if (c == '"' || c == '\\') out += '\\';
out += c;
}
return out + "\"";
}
// Indents an already formatted JSON value by one level.
std::string nested(const std::string& json) {
std::string out;
for (char c : json) {
out += c;
if (c == '\n') out += " ";
}
return out;
}
std::string object(const std::vector<std::pair<std::string, std::string>>& fields) {
if (fields.empty()) return "{}";
std::string out = "{";
for (std::size_t i = 0; i < fields.size(); ++i) {
out += i == 0 ? "\n " : ",\n ";
out += quote(fields[i].first) + ": " + nested(fields[i].second);
}
return out + "\n}";
}
struct FeeCounts {
double lowFeeCount;
double highFeeCount;
};
FeeCounts lesson007() {
const double lowFee = 2, highFee = 3, totalCount = 10, totalFees = 26;
const double det = highFee - lowFee; // determinant of [[1, 1], [lowFee, highFee]]
if (det == 0) throw std::runtime_error("Equations are not independent");
const double highFeeCount = (totalFees - lowFee * totalCount) / det;
const double lowFeeCount = totalCount - highFeeCount;
if (lowFee * lowFeeCount + highFee * highFeeCount != totalFees)
throw std::runtime_error("Solution fails verification");
const FeeCounts result{lowFeeCount, highFeeCount};
return result;
}
int main() {
const FeeCounts result = lesson007();
std::cout << object({
{"lowFeeCount", num(result.lowFeeCount)},
{"highFeeCount", num(result.highFeeCount)}
}) << "\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
{
"lowFeeCount": 4,
"highFeeCount": 6
}//! Fintech Math Bootcamp · Lesson 007 of 120
//! Linear Equations and Systems
//! Module 01: Mathematical Language and Quantitative Reasoning
//!
//! Scenario: Reconciling transaction counts and fee totals
//! Rule: x + y = 10; 2x + 3y = 26
//!
//! Try it: What if both equations are identical?
//!
//! Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/mathematical-language-and-quantitative-reasoning/linear-equations-and-systems/
//! Free course: https://courses.thefintechbuilder.com
//! Synthetic teaching example, not financial advice or a production library.
//!
//! Run it: rustc main.rs && ./main
struct FeeCounts {
low_fee_count: f64,
high_fee_count: f64,
}
fn lesson007() -> Result<FeeCounts, String> {
let (low_fee, high_fee, total_count, total_fees): (f64, f64, f64, f64) = (2.0, 3.0, 10.0, 26.0);
let det = high_fee - low_fee; // determinant of [[1, 1], [low_fee, high_fee]]
if det == 0.0 {
return Err("Equations are not independent".to_string());
}
let high_fee_count = (total_fees - low_fee * total_count) / det;
let low_fee_count = total_count - high_fee_count;
if low_fee * low_fee_count + high_fee * high_fee_count != total_fees {
return Err("Solution fails verification".to_string());
}
let result = FeeCounts { low_fee_count, high_fee_count };
Ok(result)
}
fn main() {
match lesson007() {
Ok(result) => println!(
"{}",
object(&[
("lowFeeCount", num(result.low_fee_count)),
("highFeeCount", num(result.high_fee_count)),
])
),
Err(message) => {
eprintln!("Error: {}", message);
std::process::exit(1);
}
}
}
/// Formats a number the way JSON.stringify does: shortest round-trip form, null for NaN or infinity.
fn num(x: f64) -> String {
if x.is_finite() {
format!("{}", x)
} else {
"null".to_string()
}
}
fn quote(text: &str) -> String {
format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
}
/// Indents an already formatted JSON value by one level.
fn nested(json: &str) -> String {
json.replace('\n', "\n ")
}
fn object(fields: &[(&str, String)]) -> String {
if fields.is_empty() {
return "{}".to_string();
}
let lines: Vec<String> = fields
.iter()
.map(|(key, value)| format!(" {}: {}", quote(key), nested(value)))
.collect();
format!("{{\n{}\n}}", lines.join(",\n"))
}
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
{
"lowFeeCount": 4,
"highFeeCount": 6
}/**
* Fintech Math Bootcamp · Lesson 007 of 120
* Linear Equations and Systems
* Module 01: Mathematical Language and Quantitative Reasoning
*
* Scenario: Reconciling transaction counts and fee totals
* Rule: x + y = 10; 2x + 3y = 26
*
* Try it: What if both equations are identical?
*
* Lesson article: https://thefintechbuilder.com/financial-mathematics-statistics-and-data-foundations/mathematical-language-and-quantitative-reasoning/linear-equations-and-systems/
* Free course: https://courses.thefintechbuilder.com
* Synthetic teaching example, not financial advice or a production library.
*
* Run it: dotnet run (inside a console project that holds this Program.cs)
*/
using System.Text.Json;
var jsonOptions = new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
Console.WriteLine(JsonSerializer.Serialize(Lesson007(), jsonOptions));
static FeeCounts Lesson007()
{
double lowFee = 2, highFee = 3, totalCount = 10, totalFees = 26;
var det = highFee - lowFee; // determinant of [[1, 1], [lowFee, highFee]]
if (det == 0) throw new InvalidOperationException("Equations are not independent");
var highFeeCount = (totalFees - lowFee * totalCount) / det;
var lowFeeCount = totalCount - highFeeCount;
if (lowFee * lowFeeCount + highFee * highFeeCount != totalFees)
throw new InvalidOperationException("Solution fails verification");
var result = new FeeCounts(lowFeeCount, highFeeCount);
return result;
}
record FeeCounts(double LowFeeCount, double HighFeeCount);
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
{
"lowFeeCount": 4,
"highFeeCount": 6
}Prefer your own machine? Every file is in the course repository · open it in Codespaces.
Lesson notes
The rule
x + y = 10; 2x + 3y = 26