Float32

public struct Float32 { /* private fields */ }

A 32-bit IEEE 754 single-precision float.

Range is approximately ±3.4×10^38 with 6-9 significant decimal digits. Float literals without a type annotation default to Float64; annotate the binding to pick Float32. The type is FFISafe and lays out as a single lang.f32.

Examples

let pi = Float64.pi; let area = pi * radius * radius; let s = area.format(.{precision: 2}); // "314.16" let x = 3.14; // Float64 let y: Float32 = 3.14; // Float32

Special Values

  • nan — Not-a-Number, result of 0.0 / 0.0, sqrt(-1), etc.
  • infinity / -infinity — overflow or 1.0 / 0.0.
  • Negative zero compares equal to positive zero but produces -infinity when used as a divisor.

NaN comparisons are surprising: nan == nan is false and every ordered comparison against NaN is false. Use isNaN to test, never == nan. Any arithmetic with NaN propagates NaN.

Representation

A single lang.f32 field holding the raw IEEE 754 bit pattern.

Properties

public var bitPattern: UInt32 { get }

The raw IEEE-754 bit pattern reinterpreted as an unsigned integer (UInt32 for Float32). No value conversion — the bits are preserved exactly, so sign/exponent/significand can be extracted by masking. Inverse of init(bitPattern:).

Examples

(1.0).bitPattern; // 4607182418800017408 (0x3FF0000000000000)
public static var e: Float32 { get }

Euler's number e ≈ 2.71828182845904… — base of the natural logarithm.

public static var epsilon: Float32 { get }

Machine epsilon — the smallest e such that 1.0 + e != 1.0, ≈ 1.1920929e-7.

Useful as a tolerance in approximate comparisons; scale by the operand magnitude for relative-error checks.

Examples

func almostEqual(a: Float64, b: Float64) -> Bool { (a - b).abs() < Float64.epsilon * a.abs().max(b.abs()); }
public static var infinity: Float32 { get }

Positive infinity. Produced by overflow or +x / 0.0 for x > 0. Arithmetic with infinity follows IEEE 754: finite + infinity is infinity, infinity − infinity is NaN.

Examples

Float64.infinity; // inf Float64.infinity + 1; // inf 1.0 / 0.0; // inf Float64.infinity.negate(); // -inf
public var isFinite: Bool { get }

True if self is finite — equivalently, not NaN and not infinite. Includes zero and subnormals.

public var isInfinite: Bool { get }

True if self is +infinity or -infinity.

Examples

Float64.infinity.isInfinite; // true Float64.infinity.negate().isInfinite; // true (1.0 / 0.0).isInfinite; // true Float64.nan.isInfinite; // false
public var isNaN: Bool { get }

True if self is NaN. The only correct way to test for NaN — == returns false against NaN even when both operands are NaN.

Examples

(0.0 / 0.0).isNaN; // true Float64.nan.isNaN; // true (1.0).isNaN; // false Float64.infinity.isNaN; // false
public var isNegative: Bool { get }

True if self < 0.0. False for -0.0, nan, zero, and positives. To detect signed zero specifically, use sign.

public var isNormal: Bool { get }

True if self is a normal number — finite, non-zero, and at least minPositive in magnitude. Subnormals, zero, infinity, and NaN are not normal.

Examples

(1.0).isNormal; // true (0.0).isNormal; // false Float64.minPositive.isNormal; // true (Float64.minPositive / 2.0).isNormal; // false (subnormal)
public var isPositive: Bool { get }

True if self > 0.0. False for +0.0, -0.0, nan, and negatives.

public var isSubnormal: Bool { get }

True if self is subnormal (denormalized) — finite, non-zero, and smaller than minPositive in magnitude. Subnormals trade precision for range near zero.

public var isZero: Bool { get }

True if self is +0.0 or -0.0. Both signed zeros compare equal.

public static var ln10: Float32 { get }

Natural logarithm of 10, ≈ 2.30258509299404…

public static var ln2: Float32 { get }

Natural logarithm of 2, ≈ 0.69314718055994…

public static var maxValue: Float32 { get }

The most positive finite value, ≈ 3.4028235e38.

public static var minPositive: Float32 { get }

The smallest positive normal value, ≈ 1.17549435e-38. Values smaller than this are subnormal and lose precision.

public static var minValue: Float32 { get }

The most negative finite value, ≈ -3.4028235e38.

public static var nan: Float32 { get }

Not-a-Number. Produced by undefined operations like 0.0 / 0.0 or sqrt(-1.0). NaN propagates through arithmetic and is unequal to every value including itself — always test with isNaN.

Examples

Float64.nan.isNaN; // true Float64.nan == Float64.nan; // false (!) 0.0 / 0.0; // nan
public static var pi: Float32 { get }

The constant π ≈ 3.14159265358979… — circle circumference over diameter.

public var raw: lang.f32

The underlying primitive lang.f32 value (IEEE 754 bit pattern). Exposed for FFI and intrinsic use; reach for the typed surface for everything else.

public var sign: Float32 { get }

Sign as a float: -1.0, 0.0, or 1.0. NaN propagates as NaN. Negative zero returns -0.0 (which still compares equal to 0.0).

Examples

(-3.14).sign; // -1.0 (0.0).sign; // 0.0 (3.14).sign; // 1.0 Float64.nan.sign; // nan
public static var sqrt2: Float32 { get }

Square root of 2, ≈ 1.41421356237309…

public static var tau: Float32 { get }

Tau ≈ 6.28318530717958… — equal to , often more natural for "one full turn" rotational math.

Initializers

public init()

Creates the zero value, satisfying Defaultable.

public init(floatLiteral: lang.f64)

Compiler-emitted bridge for floating-point literals via ExpressibleByFloatLiteral. Rarely called directly.

Examples

let x: Float64 = 3.14; // implicit let y = Float64(floatLiteral: 3.14); // explicit
public init(from: Float64)

Converts between Float32 and Float64. The 32→64 direction is exact; the 64→32 direction rounds and may overflow to ±infinity.

Examples

let f32: Float32 = 3.14; let f64 = Float64(from: f32);
public init(from: Int64)

Converts an Int64 to a float. Values with magnitude greater than 2^53 lose low-order bits.

Examples

let n: Int64 = 42; let f = Float64(from: n); // 42.0
init(raw: lang.f32)

Wraps an existing lang.f32 bit pattern. Internal; used by intrinsics.

public init(intLiteral: lang.i64)

Bridge that lets bare integer literals appear where a float is expected. Conversion is exact up to ±2^53; larger magnitudes round.

Examples

let x: Float64 = 42; // 42.0 let y = 3.14 + 1; // 4.14 — `1` widened to Float64
public init(parsing: String)

Parses a Float32 from a string. Recognises decimal ("3.14"), scientific ("1.5e10", "2.5E-3"), and the special tokens "inf", "-inf", "+inf", "infinity", "nan" (case-insensitive). Returns null for any other input.

Examples

Float32(parsing: "3.14"); // Some(3.14) Float32(parsing: "-2.5e10"); // Some(-2.5e10) Float32(parsing: "inf"); // Some(infinity) Float32(parsing: "nan"); // Some(nan) Float32(parsing: "abc"); // None Float32(parsing: ""); // None
public init(bitPattern: UInt32)

Constructs a float by reinterpreting a raw IEEE-754 bit pattern (the inverse of bitPattern). No value conversion — the bits are used directly.

Examples

Float32(bitPattern: 4607182418800017408); // 1.0 (Float64)

Methods

public func abs() -> Float32

Absolute value — clears the sign bit. NaN stays NaN; -0.0 becomes +0.0.

public func acos() -> Float32

Arc cosine, result in radians on [0, π]. Returns NaN outside [-1.0, 1.0].

public func acosh() -> Float32

Inverse hyperbolic cosine. Returns NaN for inputs less than 1.0.

public func asin() -> Float32

Arc sine, result in radians on [-π/2, π/2]. Returns NaN outside [-1.0, 1.0].

public func asinh() -> Float32

Inverse hyperbolic sine. Defined on all real inputs.

public func atan() -> Float32

Arc tangent, result in radians on [-π/2, π/2]. For full-quadrant recovery use atan2.

public func atan2(Float32) -> Float32

Two-argument arctangent — angle of the point (x, self) measured from the positive x-axis, on [-π, π]. Disambiguates quadrant where atan cannot.

Examples

(1.0).atan2(1.0); // π/4 (Q1) (1.0).atan2(-1.0); // 3π/4 (Q2) (-1.0).atan2(-1.0); // -3π/4 (Q3) (-1.0).atan2(1.0); // -π/4 (Q4)
public func atanh() -> Float32

Inverse hyperbolic tangent. NaN outside (-1.0, 1.0); ±inf at ±1.

public func cbrt() -> Float32

Real cube root. Defined for negatives — (-8.0).cbrt() == -2.0.

public func ceil() -> Float32

Smallest integer ≥ self. Rounds toward +infinity.

Examples

(3.2).ceil(); // 4.0 (-3.7).ceil(); // -3.0
public func clamp(Float32, Float32) -> Float32

Clamps self into [min, max]. NaN passes through unchanged. Caller must ensure min <= max.

Examples

(0.5).clamp(0.0, 1.0); // 0.5 (-0.5).clamp(0.0, 1.0); // 0.0 (1.5).clamp(0.0, 1.0); // 1.0
public func copysign(from: Float32) -> Float32

Returns a value with self's magnitude and other's sign — i.e. an IEEE 754 copysign. Useful for unbiased rounding tricks.

public func cos() -> Float32

Cosine of self in radians.

public func cosh() -> Float32

Hyperbolic cosine.

public func exp() -> Float32

e^self via libm. (-inf).exp() is 0.0; (inf).exp() is inf.

public func exp2() -> Float32

2^self. Useful for binary scaling.

public func expm1() -> Float32

e^self - 1, computed without the cancellation that hurts self.exp() - 1.0 for small self.

public func floor() -> Float32

Largest integer ≤ self. Rounds toward -infinity.

Examples

(3.7).floor(); // 3.0 (-3.2).floor(); // -4.0
public func fma(Float32, Float32) -> Float32

Fused multiply-add — (self * a) + b with a single rounding step. More accurate (and often faster) than separate multiply/add.

Examples

(2.0).fma(3.0, 4.0); // 10.0
public func fract() -> Float32

Fractional part — self - self.trunc(). Sign matches self.

Examples

(3.7).fract(); // 0.7 (-3.7).fract(); // -0.7
public func hypot(Float32) -> Float32

Hypotenuse — sqrt(self² + other²), computed via libm in a way that avoids intermediate overflow when one operand is very large.

Examples

(3.0).hypot(4.0); // 5.0
public func lerp(to: Float32, Float32) -> Float32

Linear interpolation — self + (other - self) * t. t == 0 returns self, t == 1 returns other; t outside [0, 1] extrapolates.

Examples

(0.0).lerp(to: 10.0, 0.0); // 0.0 (0.0).lerp(to: 10.0, 0.5); // 5.0 (0.0).lerp(to: 10.0, 1.0); // 10.0 (0.0).lerp(to: 10.0, 0.25); // 2.5
public func ln() -> Float32

Natural logarithm. Negatives return NaN; zero returns -inf.

Examples

(1.0).ln(); // 0.0 Float64.e.ln(); // 1.0 (0.0).ln(); // -inf (-1.0).ln(); // nan
public func ln1p() -> Float32

ln(1 + self), accurate for small self where (1.0 + self).ln() would lose digits.

public func log(Float32) -> Float32

Logarithm with arbitrary base, computed as self.ln() / base.ln(). Pick log2 or log10 directly when you can — they avoid the second libm call.

public func log10() -> Float32

Base-10 logarithm.

public func log2() -> Float32

Base-2 logarithm.

public func nextDown() -> Float32

Next representable value less than self. Mirror of nextUp.

public func nextUp() -> Float32

Next representable value greater than self. +inf and nan are fixed points; the largest finite value steps up to +inf.

public func pow(Float32) -> Float32

self ^ exponent via libm. Negative bases with non-integer exponents return NaN.

Examples

(2.0).pow(10.0); // 1024.0 (2.0).pow(0.5); // sqrt(2) (-2.0).pow(0.5); // nan
public func powi(Int64) -> Float32

Integer-exponent power via repeated squaring. Faster and more accurate than pow when the exponent is known to be integral. Negative exponents invert.

Examples

(2.0).powi(10); // 1024.0 (2.0).powi(-1); // 0.5
public func remainder(dividingBy: Float32) -> Float32

IEEE 754 remainder — uses round-to-nearest division, not truncation. Differs from %: (5.0).remainder(dividingBy: 3.0) is -1.0, not 2.0.

public func round() -> Float32

Round to nearest integer, breaking ties away from zero (banker's rounding is not used).

Examples

(3.4).round(); // 3.0 (3.5).round(); // 4.0 (tie → away from zero) (-3.5).round(); // -4.0
public func sin() -> Float32

Sine of self in radians.

public func sinCos() -> (Float32, Float32)

Sine and cosine in one call. Implemented via two libm calls today; kept for ergonomics and as a future optimisation point.

Examples

let (s, c) = angle.sinCos();
public func sinh() -> Float32

Hyperbolic sine.

public func sqrt() -> Float32

Principal square root. Negatives return NaN (-0.0 returns -0.0); +inf returns +inf.

Examples

(4.0).sqrt(); // 2.0 (-1.0).sqrt(); // nan
public func tan() -> Float32

Tangent of self in radians. Diverges to ±large near π/2 + kπ.

public func tanh() -> Float32

Hyperbolic tangent. Saturates at ±1 for large magnitudes.

public func toFloat64() -> Float64

Converts to the sibling float type. Widening (32→64) is exact; narrowing (64→32) rounds and may overflow to ±infinity.

public func toInt64() -> Int64?

Truncates toward zero into an Int64. Returns None for NaN, infinity, or values that fall outside the Int64 range.

Examples

(3.7).toInt64(); // Some(3) (-3.7).toInt64(); // Some(-3) Float64.nan.toInt64(); // None Float64.infinity.toInt64(); // None
public func trunc() -> Float32

Integer part, truncating toward zero. floor for positives, ceil for negatives.

ImplementsComparable

Associated Types

type Output = Bool

Methods

public func compare(Float32) -> Ordering

Three-way comparison returning an Ordering. NaN is not an ordered value — comparisons against NaN currently fall through to .Equal, which is wrong; gate inputs with isNaN if you need a well-defined answer.

Examples

(1.0).compare(2.0); // .Less (2.0).compare(2.0); // .Equal (3.0).compare(2.0); // .Greater (1.0).compare(Float64.infinity); // .Less
public func greaterThan(Self) -> Bool

> derived from compare.

public func greaterThanOrEqual(Self) -> Bool

>= derived from compare.

public func isAtLeast(Self) -> Bool

start.. lower-bound check, derived from compare.

public func isAtMost(Self) -> Bool

..=end upper-bound check, derived from compare.

public func isBelow(Self) -> Bool

..<end upper-bound check, derived from compare.

public func lessThan(Self) -> Bool

< derived from compare.

public func lessThanOrEqual(Self) -> Bool

<= derived from compare.

ImplementsEquatable

Associated Types

type Output = Bool

Methods

public func equal(to: Self) -> Bool

Bridges Equal.equal(to:) to Equatable.isEqual(to:).

public func isEqual(to: Float32) -> Bool

IEEE 754 equality. NaN is not equal to itself; +0.0 equals -0.0.

Examples

(3.14).isEqual(to: 3.14); // true (0.0).isEqual(to: -0.0); // true Float64.nan.isEqual(to: Float64.nan); // false (!)
public func notEqual(to: Self) -> Bool

Default !=: delegates to == so there's a single source of truth.

ImplementsLess

Associated Types

type Output = Float32
type Output = Float32
type Output = Float32
type Output = Float32
type Output = Float32
type Output = Bool
type Output = Bool
type Output = Bool
type Output = Bool

Methods

public func lessThan(Float32) -> Bool

Returns true if self < other per IEEE 754. Always false when either operand is NaN.

ImplementsLessOrEqual

Associated Types

type Output

Methods

public func lessThanOrEqual(Float32) -> Bool

Returns true if self <= other per IEEE 754. Always false when either operand is NaN.

ImplementsGreater

Associated Types

type Output

Methods

public func greaterThan(Float32) -> Bool

Returns true if self > other per IEEE 754. Always false when either operand is NaN.

ImplementsGreaterOrEqual

Associated Types

type Output

Methods

public func greaterThanOrEqual(Float32) -> Bool

Returns true if self >= other per IEEE 754. Always false when either operand is NaN.

ImplementsFormattable

Methods

public func format(into: mutating StringBuilder, FormatOptions)

Formats the float directly into writer, honouring the supplied FormatOptions. Implements Formattable.

Digit generation uses the exact big-integer engine in float_digits.ks: the value is decomposed into m * 2^e and rounded with round-to-nearest- even on the stored binary value, so printed decimals are correct.

Examples

(3.14159).format(); // "3.14159" (3.14159).format(.{precision: 2}); // "3.14" (1234.5).format(.{floatStyle: .Scientific}); // "1.2345e3" (0.756).format(.{floatStyle: .Percent}); // "75.6%" (3.14).format(.{width: 8, fill: '0'}); // "00003.14" (3.14).format(.{sign: .Always}); // "+3.14"
public func formatted(FormatOptions) -> String

Returns this value rendered as a String.

Convenience wrapper: creates a StringBuilder, calls format(into:), and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with format(into:).

ImplementsAddable

Properties

public static var zero: Float32 { get }

The additive identity, 0.0.

Associated Types

type Output

Methods

public consuming func add(consuming Float32) -> Float32

IEEE 754 addition. NaN propagates; inf + (-inf) is NaN; finite + inf is inf.

ImplementsSubtractable

Associated Types

type Output

Methods

public consuming func subtract(consuming Float32) -> Float32

IEEE 754 subtraction. inf - inf is NaN; otherwise mirrors add.

ImplementsMultipliable

Properties

public static var one: Float32 { get }

The multiplicative identity, 1.0.

Associated Types

type Output

Methods

public consuming func multiply(consuming Float32) -> Float32

IEEE 754 multiplication. NaN propagates; inf * 0 is NaN; sign of the result follows the usual algebra.

ImplementsDivisible

Associated Types

type Output

Methods

public consuming func divide(consuming Float32) -> Float32

IEEE 754 division. Unlike integer divide, dividing by zero does not trap — it produces ±infinity (or NaN for 0.0 / 0.0).

Special cases:

  • x / 0.0+inf if x > 0, -inf if x < 0, nan if x == 0
  • x / inf → 0 for finite x
  • inf / inf → NaN

Examples

(10.0).divide(4.0); // 2.5 1.0 / 0.0; // inf 0.0 / 0.0; // nan

ImplementsNegatable

Associated Types

type Output

Methods

public consuming func negate() -> Float32

IEEE 754 negation — flips the sign bit. -nan is still NaN; -(-0.0) is +0.0.

ImplementsExpressibleByFloatLiteral

Initializers

init(floatLiteral: lang.f64)

Builds an instance from a floating-point literal.

ImplementsExpressibleByIntLiteral

Initializers

init(intLiteral: lang.i64)

Builds an instance from an integer literal.

ImplementsDefaultable

Initializers

init()

Builds the default-valued instance.

ImplementsConvertible

Initializers

init(from: From)

Creates an instance from value.

Defined in lang/std/numeric/float32.ks