or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

arithmetic.mddata-types.mdexpressions.mdindex.mdmatrices.mdprobability.mdstatistics.mdtrigonometry.mdunits.md

units.mddocs/

0

# Units and Conversions

1

2

This document covers Math.js's comprehensive unit system, including unit creation, conversion, arithmetic with units, and the extensive built-in unit library covering physical quantities, measurements, and conversions.

3

4

## Import

5

6

```typescript

7

import {

8

// Core unit functions

9

unit, to, createUnit, splitUnit, toBest,

10

// Unit-related utilities

11

isUnit, hasNumericValue,

12

// Mathematical operations (work with units)

13

add, subtract, multiply, divide, pow, sqrt,

14

// Constants with units (physical constants)

15

speedOfLight, planckConstant, electronMass, avogadro

16

} from 'mathjs'

17

```

18

19

## Basic Unit Creation and Usage

20

21

### Creating Units

22

23

```typescript

24

unit(value?: string | number, unit?: string): Unit

25

```

26

{ .api }

27

28

```typescript

29

// Create units from strings

30

unit('5 meter') // 5 meter

31

unit('10 cm') // 10 cm

32

unit('3.5 kg') // 3.5 kg

33

unit('25 celsius') // 25 celsius

34

35

// Create dimensionless units

36

unit('5') // Just the number 5

37

unit() // Dimensionless 1

38

39

// Create units with separate value and unit

40

unit(5, 'meter') // 5 meter

41

unit(3.14159, 'radian') // π radians

42

43

// Complex values with units

44

unit(complex(3, 4), 'meter') // (3+4i) meter

45

unit(fraction(1, 3), 'hour') // 1/3 hour

46

47

// From expressions

48

unit('5 * 3 meter') // 15 meter

49

unit('sqrt(16) kg') // 4 kg

50

```

51

52

### Unit Conversion

53

54

```typescript

55

to(value: Unit, unit: string | Unit): Unit

56

```

57

{ .api }

58

59

```typescript

60

// Basic conversions

61

const distance = unit('5 km')

62

to(distance, 'meter') // 5000 meter

63

to(distance, 'mile') // ~3.10686 mile

64

to(distance, 'inch') // ~196850 inch

65

66

// Temperature conversions

67

const temp = unit('100 celsius')

68

to(temp, 'fahrenheit') // 212 fahrenheit

69

to(temp, 'kelvin') // 373.15 kelvin

70

71

// Time conversions

72

const time = unit('2 hours')

73

to(time, 'minute') // 120 minute

74

to(time, 'second') // 7200 second

75

76

// Area conversions

77

const area = unit('1 m^2')

78

to(area, 'cm^2') // 10000 cm^2

79

to(area, 'ft^2') // ~10.7639 ft^2

80

81

// Volume conversions

82

const volume = unit('1 liter')

83

to(volume, 'gallon') // ~0.264172 gallon

84

to(volume, 'm^3') // 0.001 m^3

85

86

// Compound units

87

const speed = unit('60 mile/hour')

88

to(speed, 'km/h') // ~96.5606 km/h

89

to(speed, 'm/s') // ~26.8224 m/s

90

```

91

92

### Automatic Best Unit Selection

93

94

```typescript

95

toBest(value: Unit, options?: ToBestOptions): Unit

96

```

97

{ .api }

98

99

```typescript

100

interface ToBestOptions {

101

system?: 'si' | 'us' | 'imperial' | 'metric'

102

}

103

```

104

105

```typescript

106

// Automatically choose the most readable unit

107

toBest(unit('0.001 m')) // 1 mm

108

toBest(unit('1000 m')) // 1 km

109

toBest(unit('3600 second')) // 1 hour

110

111

// With system preference

112

toBest(unit('1000 meter'), { system: 'us' }) // ~0.621371 mile

113

toBest(unit('1 kg'), { system: 'us' }) // ~2.20462 lb

114

115

// For very large or small quantities

116

toBest(unit('0.000001 meter')) // 1 micrometer

117

toBest(unit('1000000 gram')) // 1 tonne

118

```

119

120

## Unit Arithmetic

121

122

### Basic Operations with Units

123

124

```typescript

125

// Addition and subtraction (units must be compatible)

126

add(unit('5 meter'), unit('3 meter')) // 8 meter

127

add(unit('2 km'), unit('500 m')) // 2.5 km (automatic conversion)

128

subtract(unit('10 inch'), unit('2 inch')) // 8 inch

129

130

// Multiplication and division

131

multiply(unit('5 meter'), unit('3 meter')) // 15 meter^2

132

multiply(unit('60 km'), unit('2 hour')) // Error: incompatible for this operation

133

divide(unit('60 km'), unit('2 hour')) // 30 km/hour

134

135

// With scalars

136

multiply(unit('5 meter'), 3) // 15 meter

137

divide(unit('10 kg'), 2) // 5 kg

138

139

// Powers and roots

140

pow(unit('5 meter'), 2) // 25 meter^2

141

pow(unit('8 m^3'), 1/3) // 2 meter

142

sqrt(unit('16 meter^2')) // 4 meter

143

```

144

145

### Complex Unit Operations

146

147

```typescript

148

// Force calculation: F = ma

149

const mass = unit('5 kg')

150

const acceleration = unit('10 m/s^2')

151

const force = multiply(mass, acceleration) // 50 N (automatically converts to Newtons)

152

153

// Energy calculation: E = 0.5 * m * v^2

154

const velocity = unit('20 m/s')

155

const kineticEnergy = multiply(0.5, multiply(mass, pow(velocity, 2))) // 1000 J

156

157

// Pressure calculation: P = F/A

158

const area = unit('2 m^2')

159

const pressure = divide(force, area) // 25 Pa

160

161

// Electrical calculations

162

const voltage = unit('12 V')

163

const current = unit('2 A')

164

const power = multiply(voltage, current) // 24 W

165

const resistance = divide(voltage, current) // 6 ohm

166

```

167

168

## Creating Custom Units

169

170

### Simple Custom Units

171

172

```typescript

173

createUnit(name: string, definition?: string | Unit | UnitDefinition, options?: CreateUnitOptions): Unit

174

```

175

{ .api }

176

177

```typescript

178

interface CreateUnitOptions {

179

aliases?: string[]

180

prefixes?: string

181

offset?: number

182

override?: boolean

183

}

184

```

185

186

```typescript

187

// Create simple unit based on existing unit

188

createUnit('byte') // Base unit for digital storage

189

createUnit('kilobyte', '1024 byte')

190

createUnit('megabyte', '1024 kilobyte')

191

createUnit('gigabyte', '1024 megabyte')

192

193

// Use new units

194

const storage = unit('2.5 gigabyte')

195

to(storage, 'megabyte') // 2560 megabyte

196

to(storage, 'byte') // 2684354560 byte

197

198

// Create unit with aliases

199

createUnit('dollar', { aliases: ['usd', '$'] })

200

unit('100 dollar') // 100 dollar

201

unit('50 usd') // 50 usd (same unit)

202

203

// Create derived unit

204

createUnit('mph', 'mile/hour')

205

unit('60 mph') // 60 mph

206

to(unit('60 mph'), 'm/s') // ~26.82 m/s

207

```

208

209

### Advanced Custom Units

210

211

```typescript

212

// Create unit with offset (like temperature scales)

213

createUnit('rankine', { definition: '(5/9) kelvin', offset: 0 })

214

createUnit('reaumur', { definition: '(5/4) celsius', offset: 0 })

215

216

// Create unit system

217

createUnit('furlong', '220 yard')

218

createUnit('fortnight', '14 day')

219

createUnit('speed_unusual', 'furlong/fortnight')

220

221

const unusualSpeed = unit('1 furlong/fortnight')

222

to(unusualSpeed, 'meter/second') // ~0.00000166 m/s

223

224

// Create currency units (relative values)

225

createUnit('euro', '1.1 dollar') // Exchange rate example

226

createUnit('pound', '1.3 dollar')

227

228

const price = unit('100 euro')

229

to(price, 'dollar') // 110 dollar (using defined rate)

230

```

231

232

## Built-in Unit Categories

233

234

### Length Units

235

236

```typescript

237

// Metric

238

unit('1 mm') // millimeter

239

unit('1 cm') // centimeter

240

unit('1 dm') // decimeter

241

unit('1 m') // meter

242

unit('1 km') // kilometer

243

244

// Imperial/US

245

unit('1 inch') // inch

246

unit('1 ft') // foot

247

unit('1 yard') // yard

248

unit('1 mile') // mile

249

250

// Other

251

unit('1 au') // astronomical unit

252

unit('1 lightyear') // light year

253

unit('1 parsec') // parsec

254

unit('1 angstrom') // angstrom

255

256

// Conversions

257

to(unit('1 inch'), 'cm') // 2.54 cm

258

to(unit('1 mile'), 'km') // ~1.609 km

259

to(unit('1 lightyear'), 'm') // ~9.461e15 m

260

```

261

262

### Mass and Weight Units

263

264

```typescript

265

// Metric mass

266

unit('1 mg') // milligram

267

unit('1 g') // gram

268

unit('1 kg') // kilogram

269

unit('1 tonne') // metric ton

270

271

// Imperial/US mass

272

unit('1 grain') // grain

273

unit('1 ounce') // ounce

274

unit('1 lb') // pound

275

unit('1 ton') // short ton (US)

276

unit('1 longton') // long ton (UK)

277

278

// Other

279

unit('1 carat') // carat (gemstones)

280

unit('1 atomicmass') // atomic mass unit

281

unit('1 electronmass') // electron mass

282

283

// Weight (force) units

284

unit('1 N') // newton

285

unit('1 lbf') // pound-force

286

unit('1 kgf') // kilogram-force

287

288

// Conversions

289

to(unit('1 lb'), 'kg') // ~0.453592 kg

290

to(unit('1 ounce'), 'g') // ~28.3495 g

291

```

292

293

### Time Units

294

295

```typescript

296

// Basic time

297

unit('1 ns') // nanosecond

298

unit('1 microsecond') // microsecond

299

unit('1 ms') // millisecond

300

unit('1 s') // second

301

unit('1 minute') // minute

302

unit('1 hour') // hour

303

unit('1 day') // day

304

unit('1 week') // week

305

unit('1 month') // month (30.4375 days)

306

unit('1 year') // year (365.25 days)

307

308

// Specialized

309

unit('1 decade') // 10 years

310

unit('1 century') // 100 years

311

unit('1 millennium') // 1000 years

312

313

// Conversions

314

to(unit('2 hours'), 'second') // 7200 second

315

to(unit('30 day'), 'year') // ~0.082 year

316

```

317

318

### Area Units

319

320

```typescript

321

// Metric area

322

unit('1 mm^2') // square millimeter

323

unit('1 cm^2') // square centimeter

324

unit('1 m^2') // square meter

325

unit('1 km^2') // square kilometer

326

unit('1 hectare') // hectare (10000 m^2)

327

328

// Imperial/US area

329

unit('1 in^2') // square inch

330

unit('1 ft^2') // square foot

331

unit('1 yard^2') // square yard

332

unit('1 mile^2') // square mile

333

unit('1 acre') // acre

334

335

// Conversions

336

to(unit('1 acre'), 'm^2') // ~4047 m^2

337

to(unit('1 hectare'), 'acre') // ~2.471 acre

338

```

339

340

### Volume Units

341

342

```typescript

343

// Metric volume

344

unit('1 mm^3') // cubic millimeter

345

unit('1 cm^3') // cubic centimeter

346

unit('1 dm^3') // cubic decimeter

347

unit('1 m^3') // cubic meter

348

unit('1 liter') // liter (dm^3)

349

unit('1 ml') // milliliter (cm^3)

350

351

// Imperial/US volume

352

unit('1 in^3') // cubic inch

353

unit('1 ft^3') // cubic foot

354

unit('1 gallon') // US gallon

355

unit('1 quart') // US quart

356

unit('1 pint') // US pint

357

unit('1 cup') // US cup

358

unit('1 floz') // fluid ounce

359

unit('1 tablespoon') // tablespoon

360

unit('1 teaspoon') // teaspoon

361

362

// UK Imperial

363

unit('1 gallon_imp') // Imperial gallon

364

unit('1 pint_imp') // Imperial pint

365

366

// Conversions

367

to(unit('1 gallon'), 'liter') // ~3.785 liter

368

to(unit('1 liter'), 'gallon') // ~0.264 gallon

369

to(unit('1 m^3'), 'liter') // 1000 liter

370

```

371

372

### Temperature Units

373

374

```typescript

375

// Temperature scales

376

unit('0 celsius') // Celsius

377

unit('32 fahrenheit') // Fahrenheit

378

unit('273.15 kelvin') // Kelvin

379

unit('491.67 rankine') // Rankine

380

381

// Temperature conversions (handle offset scales correctly)

382

to(unit('0 celsius'), 'fahrenheit') // 32 fahrenheit

383

to(unit('100 celsius'), 'kelvin') // 373.15 kelvin

384

to(unit('68 fahrenheit'), 'celsius') // 20 celsius

385

386

// Temperature differences (no offset)

387

const tempDiff = unit('10 degC') // 10 degree difference

388

to(tempDiff, 'degF') // 18 degF (difference)

389

```

390

391

### Speed and Velocity Units

392

393

```typescript

394

// Speed units

395

unit('1 m/s') // meter per second

396

unit('1 km/h') // kilometer per hour

397

unit('1 mph') // mile per hour

398

unit('1 ft/s') // foot per second

399

unit('1 knot') // nautical mile per hour

400

401

// Special speeds

402

unit('1 c') // speed of light

403

unit('1 mach') // speed of sound (approximate)

404

405

// Conversions

406

to(unit('60 mph'), 'km/h') // ~96.56 km/h

407

to(unit('100 km/h'), 'm/s') // ~27.78 m/s

408

to(unit('1 knot'), 'm/s') // ~0.514 m/s

409

```

410

411

### Energy and Power Units

412

413

```typescript

414

// Energy units

415

unit('1 J') // joule

416

unit('1 kJ') // kilojoule

417

unit('1 cal') // calorie

418

unit('1 kcal') // kilocalorie (food calorie)

419

unit('1 Btu') // British thermal unit

420

unit('1 kWh') // kilowatt hour

421

unit('1 eV') // electron volt

422

unit('1 erg') // erg (CGS)

423

424

// Power units

425

unit('1 W') // watt

426

unit('1 kW') // kilowatt

427

unit('1 MW') // megawatt

428

unit('1 hp') // horsepower

429

unit('1 PS') // metric horsepower

430

431

// Conversions

432

to(unit('1 kWh'), 'J') // 3600000 J

433

to(unit('1 hp'), 'W') // ~745.7 W

434

to(unit('1 cal'), 'J') // ~4.184 J

435

```

436

437

### Pressure Units

438

439

```typescript

440

// Pressure units

441

unit('1 Pa') // pascal

442

unit('1 kPa') // kilopascal

443

unit('1 MPa') // megapascal

444

unit('1 bar') // bar

445

unit('1 atm') // atmosphere

446

unit('1 mmHg') // millimeter mercury

447

unit('1 psi') // pound per square inch

448

unit('1 torr') // torr

449

450

// Conversions

451

to(unit('1 atm'), 'Pa') // 101325 Pa

452

to(unit('1 bar'), 'psi') // ~14.504 psi

453

to(unit('760 mmHg'), 'atm') // 1 atm

454

```

455

456

### Electrical Units

457

458

```typescript

459

// Basic electrical units

460

unit('1 A') // ampere (current)

461

unit('1 V') // volt (voltage)

462

unit('1 ohm') // ohm (resistance)

463

unit('1 W') // watt (power)

464

unit('1 F') // farad (capacitance)

465

unit('1 H') // henry (inductance)

466

unit('1 C') // coulomb (charge)

467

unit('1 S') // siemens (conductance)

468

469

// Derived units

470

unit('1 kW') // kilowatt

471

unit('1 mA') // milliampere

472

unit('1 kV') // kilovolt

473

unit('1 kOhm') // kiloohm

474

unit('1 uF') // microfarad

475

unit('1 mH') // millihenry

476

477

// Electrical calculations

478

const i = unit('2 A')

479

const v = unit('12 V')

480

const p = multiply(v, i) // 24 W

481

const r = divide(v, i) // 6 ohm

482

```

483

484

### Frequency and Angular Units

485

486

```typescript

487

// Frequency

488

unit('1 Hz') // hertz

489

unit('1 kHz') // kilohertz

490

unit('1 MHz') // megahertz

491

unit('1 GHz') // gigahertz

492

unit('1 rpm') // revolutions per minute

493

494

// Angular units

495

unit('1 rad') // radian

496

unit('1 deg') // degree

497

unit('1 grad') // gradian

498

unit('1 arcmin') // arc minute

499

unit('1 arcsec') // arc second

500

unit('1 revolution') // full rotation

501

502

// Conversions

503

to(unit('180 deg'), 'rad') // π rad

504

to(unit('1 revolution'), 'deg') // 360 deg

505

to(unit('60 rpm'), 'Hz') // 1 Hz

506

```

507

508

## Unit Splitting and Formatting

509

510

### Split Units into Components

511

512

```typescript

513

splitUnit(unit: Unit, parts: string[]): Unit[]

514

```

515

{ .api }

516

517

```typescript

518

// Split time into hours, minutes, seconds

519

const duration = unit('7463 second')

520

splitUnit(duration, ['hour', 'minute', 'second'])

521

// [2 hour, 4 minute, 23 second] (2h 4m 23s)

522

523

// Split length into feet and inches

524

const height = unit('73 inch')

525

splitUnit(height, ['ft', 'inch'])

526

// [6 ft, 1 inch] (6'1")

527

528

// Split weight into pounds and ounces

529

const weight = unit('2.75 lb')

530

splitUnit(weight, ['lb', 'ounce'])

531

// [2 lb, 12 ounce]

532

533

// Custom formatting with split units

534

function formatTime(seconds) {

535

const parts = splitUnit(unit(seconds, 'second'), ['hour', 'minute', 'second'])

536

return parts.map(part => part.toString()).join(' ')

537

}

538

formatTime(3661) // "1 hour 1 minute 1 second"

539

```

540

541

## Physical Constants with Units

542

543

Math.js includes many physical constants with proper units:

544

545

```typescript

546

// Fundamental constants

547

speedOfLight // ~299792458 m/s

548

planckConstant // ~6.626e-34 J*s

549

electronCharge // ~1.602e-19 C

550

electronMass // ~9.109e-31 kg

551

protonMass // ~1.673e-27 kg

552

avogadro // ~6.022e23 mol^-1

553

boltzmann // ~1.381e-23 J/K

554

gravity // 9.80665 m/s^2 (standard)

555

556

// Usage in calculations

557

const energy = multiply(electronMass, pow(speedOfLight, 2))

558

// E = mc² for electron rest energy

559

560

const force = multiply(unit('70 kg'), gravity) // Weight of 70kg person

561

to(force, 'lbf') // Convert to pounds-force

562

```

563

564

## Advanced Unit Operations

565

566

### Unit Validation and Testing

567

568

```typescript

569

// Check if value has a unit

570

isUnit(unit('5 meter')) // true

571

isUnit(5) // false

572

573

// Check if unit has numeric value

574

hasNumericValue(unit('5 meter')) // true

575

hasNumericValue(unit('meter')) // false (no numeric part)

576

577

// Get unit components

578

const speed = unit('60 km/h')

579

speed.value // 60

580

speed.units // [{ unit: 'm', power: 1 }, { unit: 's', power: -1 }] (SI base)

581

speed.toString() // "60 km / h"

582

```

583

584

### Unit Compatibility

585

586

```typescript

587

// Units are compatible if they have the same dimension

588

function areCompatible(unit1, unit2) {

589

try {

590

to(unit1, unit2.units)

591

return true

592

} catch (error) {

593

return false

594

}

595

}

596

597

areCompatible(unit('5 meter'), unit('10 foot')) // true (both length)

598

areCompatible(unit('5 kg'), unit('10 second')) // false (different dimensions)

599

600

// Get dimension of unit

601

function getDimension(unit_val) {

602

// Convert to SI base units to see fundamental dimensions

603

return unit_val.to('SI')

604

}

605

```

606

607

### Working with Dimensionless Units

608

609

```typescript

610

// Dimensionless quantities

611

unit('5') // Just number 5

612

unit('0.5') // 0.5 (could be percentage, ratio, etc.)

613

614

// Converting to dimensionless

615

const ratio = divide(unit('10 meter'), unit('5 meter')) // 2 (dimensionless)

616

617

// Angles are dimensionless but have units for clarity

618

const angle = unit('45 deg')

619

to(angle, 'rad') // π/4 rad

620

sin(angle) // sin(45°) = √2/2

621

```

622

623

## Unit System Conversions

624

625

### Metric (SI) System

626

627

```typescript

628

// Base SI units: meter, kilogram, second, ampere, kelvin, mole, candela

629

const siUnits = {

630

length: unit('1 m'),

631

mass: unit('1 kg'),

632

time: unit('1 s'),

633

current: unit('1 A'),

634

temperature: unit('1 K'),

635

amount: unit('1 mol'),

636

luminosity: unit('1 cd')

637

}

638

639

// Convert measurements to SI

640

function toSI(measurement) {

641

return measurement.to('SI')

642

}

643

```

644

645

### Imperial/US System

646

647

```typescript

648

// Common US/Imperial units

649

const usUnits = {

650

length: unit('1 ft'),

651

mass: unit('1 lb'),

652

volume: unit('1 gallon'),

653

temperature: unit('1 fahrenheit'),

654

area: unit('1 acre'),

655

speed: unit('1 mph')

656

}

657

658

// Convert between systems

659

function toMetric(usValue, targetUnit) {

660

return to(usValue, targetUnit)

661

}

662

663

toMetric(unit('70 fahrenheit'), 'celsius') // 21.11 celsius

664

toMetric(unit('60 mph'), 'km/h') // 96.56 km/h

665

```

666

667

## Performance and Memory Considerations

668

669

### Efficient Unit Operations

670

671

```typescript

672

// Pre-compile unit conversions for repeated use

673

const meterToFeet = (meters) => to(unit(meters, 'meter'), 'ft')

674

const celsiusToFahrenheit = (celsius) => to(unit(celsius, 'celsius'), 'fahrenheit')

675

676

// Batch conversions

677

const distances_m = [100, 200, 300, 500, 1000]

678

const distances_ft = distances_m.map(meterToFeet)

679

680

// Use unit arithmetic instead of converting to numbers

681

const area_m2 = multiply(unit('10 m'), unit('5 m')) // 50 m^2

682

const area_ft2 = to(area_m2, 'ft^2') // More accurate than converting first

683

```

684

685

### Working with Large Unit Systems

686

687

```typescript

688

// For applications with many custom units, create them systematically

689

function createCurrencySystem(baseCurrency, rates) {

690

Object.entries(rates).forEach(([currency, rate]) => {

691

createUnit(currency, `${rate} ${baseCurrency}`)

692

})

693

}

694

695

createCurrencySystem('USD', {

696

EUR: 0.85,

697

GBP: 0.73,

698

JPY: 110,

699

CAD: 1.25

700

})

701

702

// Now can convert between currencies

703

const price = unit('100 USD')

704

to(price, 'EUR') // 85 EUR

705

```

706

707

## Common Unit Patterns

708

709

### Engineering Calculations

710

711

```typescript

712

// Electrical engineering

713

function ohmsLaw(voltage, current, resistance) {

714

if (voltage && current) return { resistance: divide(voltage, current) }

715

if (voltage && resistance) return { current: divide(voltage, resistance) }

716

if (current && resistance) return { voltage: multiply(current, resistance) }

717

}

718

719

const result = ohmsLaw(unit('12 V'), unit('2 A'))

720

result.resistance // 6 ohm

721

722

// Mechanical engineering

723

function kineticEnergy(mass, velocity) {

724

return multiply(0.5, multiply(mass, pow(velocity, 2)))

725

}

726

727

const ke = kineticEnergy(unit('1000 kg'), unit('25 m/s'))

728

to(ke, 'kJ') // 312.5 kJ

729

730

// Fluid dynamics

731

function reynoldsNumber(density, velocity, length, viscosity) {

732

return divide(multiply(density, multiply(velocity, length)), viscosity)

733

}

734

```

735

736

### Scientific Applications

737

738

```typescript

739

// Chemistry: ideal gas law PV = nRT

740

function idealGas(pressure, volume, moles, temperature) {

741

const R = unit('8.314 J/(mol*K)') // Gas constant

742

743

if (!pressure) return divide(multiply(moles, multiply(R, temperature)), volume)

744

if (!volume) return divide(multiply(moles, multiply(R, temperature)), pressure)

745

if (!moles) return divide(multiply(pressure, volume), multiply(R, temperature))

746

if (!temperature) return divide(multiply(pressure, volume), multiply(moles, R))

747

}

748

749

// Physics: wavelength-frequency relationship

750

function wavelengthFrequency(wavelength, frequency) {

751

if (wavelength) return divide(speedOfLight, wavelength)

752

if (frequency) return divide(speedOfLight, frequency)

753

}

754

755

const freq = wavelengthFrequency(unit('500 nm')) // Green light frequency

756

to(freq, 'THz') // ~600 THz

757

```

758

759

### Everyday Calculations

760

761

```typescript

762

// Cooking conversions

763

function convertRecipe(ingredient, targetUnit) {

764

return to(ingredient, targetUnit)

765

}

766

767

convertRecipe(unit('2 cup'), 'ml') // ~473 ml

768

convertRecipe(unit('350 fahrenheit'), 'celsius') // ~177 celsius

769

770

// Travel calculations

771

function travelTime(distance, speed) {

772

return divide(distance, speed)

773

}

774

775

const time = travelTime(unit('300 km'), unit('80 km/h'))

776

to(time, 'hour') // 3.75 hour = 3h 45m

777

778

// Fuel efficiency

779

function fuelConsumption(distance, fuel) {

780

return divide(distance, fuel)

781

}

782

783

const efficiency = fuelConsumption(unit('400 mile'), unit('12 gallon'))

784

to(efficiency, 'km/l') // ~14.1 km/l

785

```

786

787

## Error Handling with Units

788

789

```typescript

790

import { DimensionError } from 'mathjs'

791

792

try {

793

// Incompatible unit operations

794

add(unit('5 meter'), unit('3 second')) // DimensionError

795

} catch (error) {

796

if (error instanceof DimensionError) {

797

console.log('Cannot add different unit dimensions')

798

}

799

}

800

801

try {

802

// Invalid unit conversion

803

to(unit('5 kg'), 'meter') // DimensionError

804

} catch (error) {

805

console.log('Cannot convert mass to length')

806

}

807

808

// Safe unit operations

809

function safeAdd(unit1, unit2) {

810

try {

811

return add(unit1, unit2)

812

} catch (error) {

813

return null // or throw custom error

814

}

815

}

816

817

function safeConvert(value, targetUnit) {

818

try {

819

return to(value, targetUnit)

820

} catch (error) {

821

return value // Return original if conversion fails

822

}

823

}

824

```

825

826

## Chain Operations with Units

827

828

```typescript

829

// Units work seamlessly with chain operations

830

const result = chain(unit('100 mile'))

831

.to('km') // Convert to kilometers

832

.multiply(2) // Double the distance

833

.divide(unit('80 km/h')) // Divide by speed to get time

834

.to('hour') // Convert to hours

835

.done() // ~5 hours

836

837

// Complex unit calculations in chain

838

const power = chain(unit('12 V'))

839

.multiply(unit('5 A')) // 60 W

840

.multiply(unit('2 hour')) // 120 Wh

841

.to('kWh') // 0.12 kWh

842

.done()

843

```