or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

collections.mdconcurrent.mdcore-features.mdindex.mdmath.mdruntime.mdutilities.md

math.mddocs/

0

# Math Operations

1

2

Mathematical functions and numeric utilities optimized for JavaScript's number system and Math object, providing Scala's math API while leveraging JavaScript's native mathematical capabilities.

3

4

## Capabilities

5

6

### Basic Mathematical Functions

7

8

Core mathematical operations adapted for JavaScript's floating-point number system.

9

10

```scala { .api }

11

/**

12

* Mathematical functions and constants

13

* Delegates to JavaScript's Math object for optimal performance

14

*/

15

object math {

16

/** Mathematical constants */

17

val E: Double = 2.718281828459045

18

val Pi: Double = 3.141592653589793

19

20

/** Absolute value */

21

def abs(x: Int): Int

22

def abs(x: Long): Long

23

def abs(x: Float): Float

24

def abs(x: Double): Double

25

26

/** Maximum of two values */

27

def max(x: Int, y: Int): Int

28

def max(x: Long, y: Long): Long

29

def max(x: Float, y: Float): Float

30

def max(x: Double, y: Double): Double

31

32

/** Minimum of two values */

33

def min(x: Int, y: Int): Int

34

def min(x: Long, y: Long): Long

35

def min(x: Float, y: Float): Float

36

def min(x: Double, y: Double): Double

37

38

/** Sign of number (-1, 0, or 1) */

39

def signum(x: Int): Int

40

def signum(x: Long): Long

41

def signum(x: Float): Float

42

def signum(x: Double): Double

43

44

/** Power function */

45

def pow(x: Double, y: Double): Double

46

47

/** Square root */

48

def sqrt(x: Double): Double

49

50

/** Cubic root */

51

def cbrt(x: Double): Double

52

53

/** Hypotenuse (sqrt(x² + y²)) */

54

def hypot(x: Double, y: Double): Double

55

56

/** Exponential function (e^x) */

57

def exp(x: Double): Double

58

59

/** Natural logarithm */

60

def log(x: Double): Double

61

62

/** Base-10 logarithm */

63

def log10(x: Double): Double

64

65

/** Ceiling (smallest integer >= x) */

66

def ceil(x: Double): Double

67

68

/** Floor (largest integer <= x) */

69

def floor(x: Double): Double

70

71

/** Round to nearest integer */

72

def round(x: Float): Int

73

def round(x: Double): Long

74

75

/** Round toward zero */

76

def truncate(x: Double): Double

77

78

/** Remainder after division */

79

def IEEEremainder(x: Double, y: Double): Double

80

}

81

82

/**

83

* Random number generator using JavaScript's Math.random()

84

* Provides utility methods for common random operations

85

*/

86

class Random(seed: Long = System.currentTimeMillis()) {

87

def nextBoolean(): Boolean

88

def nextInt(): Int

89

def nextInt(n: Int): Int

90

def nextLong(): Long

91

def nextFloat(): Float

92

def nextDouble(): Double

93

def nextGaussian(): Double

94

def nextBytes(bytes: Array[Byte]): Unit

95

def shuffle[T](array: Array[T]): Unit

96

}

97

98

object Random {

99

def apply(): Random

100

def apply(seed: Long): Random

101

}

102

```

103

104

### Trigonometric Functions

105

106

Complete set of trigonometric and hyperbolic functions using JavaScript's Math implementation.

107

108

```scala { .api }

109

object math {

110

/** Trigonometric functions (radians) */

111

def sin(x: Double): Double

112

def cos(x: Double): Double

113

def tan(x: Double): Double

114

115

/** Inverse trigonometric functions */

116

def asin(x: Double): Double

117

def acos(x: Double): Double

118

def atan(x: Double): Double

119

def atan2(y: Double, x: Double): Double

120

121

/** Hyperbolic functions */

122

def sinh(x: Double): Double

123

def cosh(x: Double): Double

124

def tanh(x: Double): Double

125

126

/** Convert degrees to radians */

127

def toRadians(angdeg: Double): Double

128

129

/** Convert radians to degrees */

130

def toDegrees(angrad: Double): Double

131

}

132

```

133

134

### Numeric Type Utilities

135

136

Utilities for working with different numeric types and their limits.

137

138

```scala { .api }

139

/**

140

* Numeric type companion objects with constants and utilities

141

*/

142

object Int {

143

/** Minimum and maximum values */

144

val MinValue: Int = -2147483648

145

val MaxValue: Int = 2147483647

146

}

147

148

object Long {

149

val MinValue: Long = -9223372036854775808L

150

val MaxValue: Long = 9223372036854775807L

151

}

152

153

object Float {

154

val MinValue: Float = -3.4028235e38f

155

val MaxValue: Float = 3.4028235e38f

156

val MinPositiveValue: Float = 1.4e-45f

157

val PositiveInfinity: Float = Float.PositiveInfinity

158

val NegativeInfinity: Float = Float.NegativeInfinity

159

val NaN: Float = Float.NaN

160

}

161

162

object Double {

163

val MinValue: Double = -1.7976931348623157e308

164

val MaxValue: Double = 1.7976931348623157e308

165

val MinPositiveValue: Double = 4.9e-324

166

val PositiveInfinity: Double = Double.PositiveInfinity

167

val NegativeInfinity: Double = Double.NegativeInfinity

168

val NaN: Double = Double.NaN

169

}

170

171

/**

172

* BigInt for arbitrary precision integers

173

* Uses JavaScript BigInt when available, falls back to string-based implementation

174

*/

175

class BigInt(val bigInteger: java.math.BigInteger) {

176

/** Basic arithmetic operations */

177

def +(that: BigInt): BigInt

178

def -(that: BigInt): BigInt

179

def *(that: BigInt): BigInt

180

def /(that: BigInt): BigInt

181

def %(that: BigInt): BigInt

182

183

/** Comparison operations */

184

def <(that: BigInt): Boolean

185

def <=(that: BigInt): Boolean

186

def >(that: BigInt): Boolean

187

def >=(that: BigInt): Boolean

188

189

/** Bitwise operations */

190

def &(that: BigInt): BigInt

191

def |(that: BigInt): BigInt

192

def ^(that: BigInt): BigInt

193

def unary_~ : BigInt

194

195

/** Conversion methods */

196

def toInt: Int

197

def toLong: Long

198

def toFloat: Float

199

def toDouble: Double

200

override def toString: String

201

def toString(radix: Int): String

202

}

203

204

object BigInt {

205

/** Create BigInt from various types */

206

def apply(x: Int): BigInt

207

def apply(x: Long): BigInt

208

def apply(x: String): BigInt

209

def apply(x: String, radix: Int): BigInt

210

211

/** Predefined constants */

212

val 0: BigInt

213

val 1: BigInt

214

val 2: BigInt

215

val 10: BigInt

216

}

217

218

/**

219

* BigDecimal for arbitrary precision decimal numbers

220

*/

221

class BigDecimal(val bigDecimal: java.math.BigDecimal) {

222

/** Arithmetic operations with precision control */

223

def +(that: BigDecimal): BigDecimal

224

def -(that: BigDecimal): BigDecimal

225

def *(that: BigDecimal): BigDecimal

226

def /(that: BigDecimal): BigDecimal

227

def %(that: BigDecimal): BigDecimal

228

229

/** Precision and scale */

230

def precision: Int

231

def scale: Int

232

def setScale(newScale: Int): BigDecimal

233

def setScale(newScale: Int, roundingMode: RoundingMode): BigDecimal

234

235

/** Comparison */

236

def compare(that: BigDecimal): Int

237

238

/** Conversion */

239

def toDouble: Double

240

def toFloat: Float

241

def toLong: Long

242

def toInt: Int

243

override def toString: String

244

}

245

246

object BigDecimal {

247

/** Create BigDecimal from various types */

248

def apply(x: Int): BigDecimal

249

def apply(x: Long): BigDecimal

250

def apply(x: Double): BigDecimal

251

def apply(x: String): BigDecimal

252

253

/** Rounding modes */

254

object RoundingMode extends Enumeration {

255

val UP, DOWN, CEILING, FLOOR, HALF_UP, HALF_DOWN, HALF_EVEN, UNNECESSARY = Value

256

}

257

}

258

```

259

260

**Usage Examples:**

261

262

```scala

263

import scala.math._

264

265

// Basic mathematical operations

266

val distance = sqrt(pow(3, 2) + pow(4, 2)) // Pythagorean theorem

267

println(s"Distance: $distance") // 5.0

268

269

val area = Pi * pow(5, 2) // Circle area

270

println(f"Circle area: $area%.2f")

271

272

// Trigonometric calculations

273

val angle = toRadians(45) // Convert 45 degrees to radians

274

val sinValue = sin(angle)

275

val cosValue = cos(angle)

276

println(f"sin(45°) = $sinValue%.3f, cos(45°) = $cosValue%.3f")

277

278

// Finding angles

279

val opposite = 3.0

280

val adjacent = 4.0

281

val angleRad = atan2(opposite, adjacent)

282

val angleDeg = toDegrees(angleRad)

283

println(f"Angle: $angleDeg%.1f degrees")

284

285

// Rounding and precision

286

val value = 3.14159

287

println(s"Ceiling: ${ceil(value)}") // 4.0

288

println(s"Floor: ${floor(value)}") // 3.0

289

println(s"Rounded: ${round(value)}") // 3

290

291

// Min/max operations

292

val numbers = List(3.7, 1.2, 8.9, 2.1, 5.5)

293

val minimum = numbers.reduce(min)

294

val maximum = numbers.reduce(max)

295

println(s"Range: $minimum to $maximum")

296

297

// Working with limits

298

println(s"Int range: ${Int.MinValue} to ${Int.MaxValue}")

299

println(s"Double max: ${Double.MaxValue}")

300

301

// Special values

302

val result1 = 1.0 / 0.0 // Positive infinity

303

val result2 = -1.0 / 0.0 // Negative infinity

304

val result3 = 0.0 / 0.0 // NaN

305

306

println(s"Is infinite: ${result1.isInfinite}")

307

println(s"Is NaN: ${result3.isNaN}")

308

309

// BigInt for large integers

310

val big1 = BigInt("12345678901234567890")

311

val big2 = BigInt("98765432109876543210")

312

val bigSum = big1 + big2

313

val bigProduct = big1 * big2

314

315

println(s"Big sum: $bigSum")

316

println(s"Big product length: ${bigProduct.toString.length} digits")

317

318

// BigDecimal for precise decimal arithmetic

319

val price1 = BigDecimal("19.99")

320

val price2 = BigDecimal("29.99")

321

val tax = BigDecimal("0.08")

322

323

val subtotal = price1 + price2

324

val taxAmount = subtotal * tax

325

val total = subtotal + taxAmount

326

327

println(f"Subtotal: $$${subtotal}")

328

println(f"Tax: $$${taxAmount.setScale(2, BigDecimal.RoundingMode.HALF_UP)}")

329

println(f"Total: $$${total.setScale(2, BigDecimal.RoundingMode.HALF_UP)}")

330

331

// Mathematical sequences

332

def factorial(n: Int): BigInt = {

333

if (n <= 1) BigInt(1)

334

else BigInt(n) * factorial(n - 1)

335

}

336

337

val fact10 = factorial(10)

338

println(s"10! = $fact10")

339

340

// Geometric calculations

341

def distanceBetweenPoints(x1: Double, y1: Double, x2: Double, y2: Double): Double = {

342

sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2))

343

}

344

345

val dist = distanceBetweenPoints(0, 0, 3, 4)

346

println(f"Distance between points: $dist%.2f")

347

348

// Exponential and logarithmic functions

349

val growth = exp(0.05 * 10) // 5% growth over 10 periods

350

val halfLife = log(0.5) / log(0.95) // Half-life with 5% decay rate

351

352

println(f"10-period growth: ${growth * 100 - 100}%.1f%%")

353

println(f"Half-life: $halfLife%.1f periods")

354

```

355

356

### Random Number Generation

357

358

Random number utilities integrated with JavaScript's Math.random() and providing additional distributions.

359

360

```scala { .api }

361

/**

362

* Random number generator using JavaScript's Math.random()

363

* Provides additional utility methods for common random operations

364

*/

365

class Random(seed: Long = System.currentTimeMillis()) {

366

/** Generate random boolean */

367

def nextBoolean(): Boolean

368

369

/** Generate random integer in full range */

370

def nextInt(): Int

371

372

/** Generate random integer from 0 to n-1 */

373

def nextInt(n: Int): Int

374

375

/** Generate random long */

376

def nextLong(): Long

377

378

/** Generate random float from 0.0 to 1.0 */

379

def nextFloat(): Float

380

381

/** Generate random double from 0.0 to 1.0 */

382

def nextDouble(): Double

383

384

/** Generate random Gaussian (normal) distribution */

385

def nextGaussian(): Double

386

387

/** Fill array with random bytes */

388

def nextBytes(bytes: Array[Byte]): Unit

389

390

/** Shuffle array in place */

391

def shuffle[T](array: Array[T]): Unit

392

}

393

394

object Random {

395

/** Default random instance */

396

def apply(): Random = new Random()

397

398

/** Seeded random instance */

399

def apply(seed: Long): Random = new Random(seed)

400

}

401

```

402

403

**Usage Examples:**

404

405

```scala

406

import scala.util.Random

407

408

val random = new Random()

409

410

// Basic random generation

411

val randomInt = random.nextInt(100) // 0 to 99

412

val randomDouble = random.nextDouble() // 0.0 to 1.0

413

val randomBoolean = random.nextBoolean()

414

415

println(s"Random int: $randomInt")

416

println(f"Random double: $randomDouble%.3f")

417

println(s"Random boolean: $randomBoolean")

418

419

// Random selection from collection

420

val colors = Array("red", "green", "blue", "yellow", "purple")

421

val randomColor = colors(random.nextInt(colors.length))

422

println(s"Random color: $randomColor")

423

424

// Random range generation

425

def randomRange(min: Int, max: Int): Int = {

426

min + random.nextInt(max - min + 1)

427

}

428

429

val diceRoll = randomRange(1, 6)

430

println(s"Dice roll: $diceRoll")

431

432

// Gaussian distribution for natural variation

433

val baseValue = 100.0

434

val variation = random.nextGaussian() * 10 // Standard deviation of 10

435

val naturalValue = baseValue + variation

436

println(f"Natural variation: $naturalValue%.1f")

437

438

// Shuffling collections

439

val deck = (1 to 52).toArray

440

random.shuffle(deck)

441

println(s"Shuffled deck (first 5): ${deck.take(5).mkString(", ")}")

442

443

// Weighted random selection

444

def weightedChoice[T](items: List[(T, Double)]): T = {

445

val totalWeight = items.map(_._2).sum

446

val randomValue = random.nextDouble() * totalWeight

447

448

var cumulativeWeight = 0.0

449

for ((item, weight) <- items) {

450

cumulativeWeight += weight

451

if (randomValue <= cumulativeWeight) {

452

return item

453

}

454

}

455

items.last._1 // Fallback

456

}

457

458

val outcomes = List(

459

("common", 0.7),

460

("uncommon", 0.2),

461

("rare", 0.08),

462

("legendary", 0.02)

463

)

464

465

val result = weightedChoice(outcomes)

466

println(s"Random outcome: $result")

467

468

// Seeded random for reproducible results

469

val seededRandom = new Random(12345)

470

val sequence1 = (1 to 5).map(_ => seededRandom.nextInt(100))

471

472

val seededRandom2 = new Random(12345) // Same seed

473

val sequence2 = (1 to 5).map(_ => seededRandom2.nextInt(100))

474

475

println(s"Sequence 1: ${sequence1.mkString(", ")}")

476

println(s"Sequence 2: ${sequence2.mkString(", ")}")

477

println(s"Sequences match: ${sequence1 == sequence2}") // true

478

```