Skip to content

feat: add comprehensive energy unit conversion module#1014

Merged
siriak merged 1 commit intoTheAlgorithms:masterfrom
AliAlimohammadi:add-energy-conversion
Feb 7, 2026
Merged

feat: add comprehensive energy unit conversion module#1014
siriak merged 1 commit intoTheAlgorithms:masterfrom
AliAlimohammadi:add-energy-conversion

Conversation

@AliAlimohammadi
Copy link
Contributor

@AliAlimohammadi AliAlimohammadi commented Feb 7, 2026

Description

This PR adds a new energy conversion module to the conversions library, enabling conversion between 70+ energy units across different measurement systems and scientific disciplines.

Implementation

Design Decisions

  • SI-based conversions: All conversions route through joules (the SI base unit) as an intermediary, ensuring consistency and accuracy
  • Two-step conversion: Follows the established pattern of to_joule()joule_to_unit() for clarity and maintainability
  • Type-safe enum API: Uses EnergyUnit enum matching the repository's temperature.rs pattern for compile-time safety
  • Pattern matching: Consolidates equivalent units (e.g., Joule | WattSecond | NewtonMeter) for cleaner code

Supported Units (70+ units)

SI Units (8)

  • Joule, kilojoule, megajoule, gigajoule
  • Millijoule, microjoule, nanojoule, attojoule

Power-Time Units (6)

  • Watt-second, watt-hour, kilowatt-second, kilowatt-hour
  • Megawatt-hour, gigawatt-hour

Mechanical Units (3)

  • Newton-meter, erg, dyne-centimeter

Calorie Variants (6)

  • Nutritional calorie, nutritional kilocalorie
  • IT calorie, IT kilocalorie
  • Thermochemical calorie, thermochemical kilocalorie

Electron Volt Units (3)

  • Electronvolt (eV), kiloelectronvolt (keV), megaelectronvolt (MeV)

British Thermal Units (3)

  • BTU (IT), BTU (thermochemical), mega BTU (IT)

Imperial Force-Distance Units (7)

  • Foot-pound, pound-force foot, pound-force inch
  • Inch-pound, inch-ounce, ounce-force inch, poundal foot

Horsepower Units (2)

  • Horsepower hour, metric horsepower hour

Metric Force Units (5)

  • Kilogram-force meter, kilogram-force centimeter, kilopond meter
  • Gram-force meter, gram-force centimeter

Therm Units (3)

  • Therm, therm (EC), therm (US)

Specialized Units (7)

  • Ton-hour refrigeration
  • Fuel oil equivalent (kiloliter), fuel oil equivalent (barrel)
  • Ton of TNT, kiloton, megaton, gigaton

Atomic Units (2)

  • Hartree energy, Rydberg constant

Testing

Test Coverage

  • 40+ comprehensive tests covering all major unit categories
  • Round-trip conversions verify accuracy in both directions for 8 common units
  • Same-unit conversions ensure identity operations work correctly
  • Edge cases including zero values, negative values, and large values
  • Cross-system conversions (e.g., SI ↔ Imperial, calories ↔ joules, eV ↔ joules)
  • Unit equivalence tests verify that equivalent units (e.g., foot-pound vs pound-force foot) convert identically
  • Real-world scenarios (food energy, electricity bills, explosive yields, atomic physics)

Test Organization

All tests use the approx_eq() helper for floating-point comparisons with appropriate tolerances, ensuring robust validation across the full range of energy scales from attojoules to gigatons.

Verification

cargo test energy::        # Run all energy tests
cargo clippy              # Zero warnings
cargo fmt --check         # Properly formatted

Code Quality

  • Documentation: Comprehensive module and function documentation with usage examples
  • Type Safety: Enum prevents invalid unit specifications at compile time
  • Precision: Uses f64 for all calculations with appropriate tolerance checks (EPSILON = 1e-10)
  • Consistency: Exactly matches existing temperature.rs module pattern
  • No Dependencies: Uses only standard library
  • Clean Code: Zero clippy warnings, properly formatted

Examples

use the_algorithms_rust::conversions::energy::{convert_energy, EnergyUnit};

// Electricity billing
let kwh_to_joules = convert_energy(100.0, EnergyUnit::KilowattHour, EnergyUnit::Joule);
// 100 kWh = 360,000,000 J

// Food nutrition
let calories = convert_energy(2000.0, EnergyUnit::CalorieNutritional, EnergyUnit::Kilojoule);
// 2000 Cal ≈ 8,374 kJ

// Physics calculations
let electron_volts = convert_energy(1.0, EnergyUnit::Joule, EnergyUnit::Electronvolt);
// 1 J ≈ 6.242×10¹⁸ eV

// Engineering applications
let btu_to_kwh = convert_energy(3412.0, EnergyUnit::BtuIT, EnergyUnit::KilowattHour);
// 3412 BTU ≈ 1 kWh

// Explosive energy
let megaton_to_gj = convert_energy(1.0, EnergyUnit::Megaton, EnergyUnit::Gigajoule);
// 1 megaton TNT = 4,184,000 GJ

References

All conversion factors are based on authoritative sources:

Checklist

  • Code follows the repository's style guidelines
  • Self-review of code completed
  • Code is well-commented with comprehensive documentation
  • Corresponding documentation added
  • No new warnings generated (cargo clippy passes with zero warnings)
  • All tests pass (cargo test shows 100% pass rate)
  • Follows the same pattern as existing conversion modules (matches temperature.rs)
  • Module added to mod.rs with proper exports

@AliAlimohammadi
Copy link
Contributor Author

@siriak, this is ready to be merged.

@codecov-commenter
Copy link

Codecov Report

❌ Patch coverage is 81.75439% with 52 lines in your changes missing coverage. Please review.
✅ Project coverage is 95.98%. Comparing base (d0536ba) to head (4263563).

Files with missing lines Patch % Lines
src/conversions/energy.rs 81.75% 52 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1014      +/-   ##
==========================================
- Coverage   96.12%   95.98%   -0.14%     
==========================================
  Files         380      381       +1     
  Lines       28250    28535     +285     
==========================================
+ Hits        27154    27388     +234     
- Misses       1096     1147      +51     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@siriak siriak merged commit a468046 into TheAlgorithms:master Feb 7, 2026
7 checks passed
@AliAlimohammadi AliAlimohammadi deleted the add-energy-conversion branch February 7, 2026 21:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants