quantity-logarithmic.dhover×265all
#!/usr/bin/env dub
/+ dub.sdl:
    name "uom_quantity_logarithmic"
    targetPath "build"
+/
/**
 * Units of measure — logarithmic quantities (photographic stops / decibels),
 * and *why* they resist the free-abelian-group exponent-vector model.
 *
 * A physically-based raytracer accumulates *linear* radiance
 * (W·m⁻²·sr⁻¹); a photographer's exposure controls are *logarithmic*. One
 * photographic **stop** (an exposure value, EV, base-2) *doubles* exposure;
 * power **decibels** obey `+3 dB ≈ ×2` power (the familiar `+6 dB ≈ ×2` is the
 * amplitude/field convention, `20·log₁₀`). The defining move is that
 * LOG-DOMAIN ADDITION corresponds to LINEAR-DOMAIN MULTIPLICATION:
 * stacking `+1 EV` then `+2 EV` gives `+3 EV`, which scales linear radiance by
 * `×2 · ×4 = ×8`. We model `struct Stops { double ev; }` whose `+`/`-` compose
 * gains, with a `toLinear()`/`fromLinear()` bridge to a plain multiplicative
 * `Ratio`, and prove the homomorphism both ways.
 *
 * This is exactly why logarithmic units are a "fourfold silence" in the theory
 * tree (comparison #9): a stop is **not a grade in the dimension group**. It
 * carries no exponent vector — its underlying `Ratio` is *dimensionless* — yet
 * its `+` means `×` on that ratio, so the `ℤⁿ` exponent-vector algebra, whose
 * `+` is ordinary linear addition within a grade, represents the wrong
 * operation. A `Stops` is instead the isomorphism `log₂ : (ℝ_{>0}, ×) → (ℝ, +)`
 * — a re-coordinatization of the dimensionless ratios — and it is only
 * meaningful *relative to a reference* (a base exposure; a reference power).
 * The bridge `2^ev` is nonlinear, so a *vector* of log-values is nonlinear too:
 * you cannot component-add exposures the way you add displacements (§ below).
 *
 * Companion to docs/research/units-of-measure/python-pint.md (the only shipped
 * dB unit) and docs/research/units-of-measure/julia-unitful.md (the
 * experimental log layer); see comparison.md #9 (Angle & logarithmic policy).
 *
 * Composition: `Stops` is scalar here, but a per-RGB-channel exposure would be
 * `Vector!(Stops, 3)` (ordering B) — a *product* structure, not a vector space,
 * because component-adding stop vectors component-*multiplies* the linear RGB
 * gains and does NOT distribute over radiance addition; a single scalar `Stops`
 * acting on a dimensioned radiance `Quantity!(dim, Vec3)` (ordering A) is the
 * only composition that stays linear-algebra-clean.
 *
 * Run with: `dub run --single quantity-logarithmic.d`
 */
module 
(module) uom_quantity_logarithmic

Units of measure — logarithmic quantities (photographic stops / decibels), and why they resist the free-abelian-group exponent-vector model.

A physically-based raytracer accumulates linear radiance (W·m⁻²·sr⁻¹); a photographer's exposure controls are logarithmic. One photographic stop (an exposure value, EV, base-2) doubles exposure; power decibels obey +3 dB ≈ ×2 power (the familiar +6 dB ≈ ×2 is the amplitude/field convention, 20·log₁₀). The defining move is that LOG-DOMAIN ADDITION corresponds to LINEAR-DOMAIN MULTIPLICATION: stacking +1 EV then +2 EV gives +3 EV, which scales linear radiance by ×2 · ×4 = ×8. We model struct Stops { double ev; } whose +/- compose gains, with a toLinear()/fromLinear() bridge to a plain multiplicative Ratio, and prove the homomorphism both ways.

This is exactly why logarithmic units are a "fourfold silence" in the theory tree (comparison #9): a stop is not a grade in the dimension group. It carries no exponent vector — its underlying Ratio is dimensionless — yet its + means × on that ratio, so the ℤⁿ exponent-vector algebra, whose + is ordinary linear addition within a grade, represents the wrong operation. A Stops is instead the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +) — a re-coordinatization of the dimensionless ratios — and it is only meaningful relative to a reference (a base exposure; a reference power). The bridge 2^ev is nonlinear, so a vector of log-values is nonlinear too: you cannot component-add exposures the way you add displacements (§ below).

Companion to docs/research/units-of-measure/python-pint.md (the only shipped dB unit) and docs/research/units-of-measure/julia-unitful.md (the experimental log layer); see comparison.md #9 (Angle & logarithmic policy).

Composition

Stops is scalar here, but a per-RGB-channel exposure would be Vector!(Stops, 3) (ordering B) — a product structure, not a vector space, because component-adding stop vectors component-multiplies the linear RGB gains and does NOT distribute over radiance addition; a single scalar Stops acting on a dimensioned radiance Quantity!(dim, Vec3) (ordering A) is the only composition that stays linear-algebra-clean.

Run with: dub run --single quantity-logarithmic.d

uom_quantity_logarithmic
;
import
(package) std
std
.
(module) std.math

Contains the elementary mathematical functions (powers, roots, and trigonometric functions), and low-level floating-point operations. Mathematical special functions are available in std.mathspecial.

Category Members
Constants E PI PI_2 PI4 M1_PI M2_PI M2_SQRTPI LN10 LN2 LOG2 LOG2E LOG2T LOG10E SQRT2 SQRT1_2
Algebraic abs fabs sqrt cbrt hypot poly nextPow2 truncPow2
Trigonometry sin cos tan asin acos atan atan2 sinh cosh tanh asinh acosh atanh
Rounding ceil floor round lround trunc rint lrint nearbyint rndtol quantize
Exponentiation & Logarithms pow powmod exp exp2 expm1 ldexp frexp log log2 log10 logb ilogb log1p scalbn
Remainder fmod modf remainder remquo
Floating-point operations approxEqual feqrel fdim fmax fmin fma isClose nextDown nextUp nextafter NaN getNaNPayload cmp
Introspection isFinite isIdentical isInfinity isNaN isNormal isSubnormal signbit sgn copysign isPowerOf2
Hardware Control IeeeFlags ieeeFlags resetIeeeFlags FloatingPointControl

The functionality closely follows the IEEE754-2008 standard for floating-point arithmetic, including the use of camelCase names rather than C99-style lower case names. All of these functions behave correctly when presented with an infinity or NaN.

The following IEEE 'real' formats are currently supported:

  • 64 bit Big-endian 'double' (eg PowerPC)

  • 128 bit Big-endian 'quadruple' (eg SPARC)

  • 64 bit Little-endian 'double' (eg x86-SSE2)

  • 80 bit Little-endian, with implied bit 'real80' (eg x87, Itanium)

  • 128 bit Little-endian 'quadruple' (not implemented on any known processor!)

  • Non-IEEE 128 bit Big-endian 'doubledouble' (eg PowerPC) has partial support

Unlike C, there is no global 'errno' variable. Consequently, almost all of these functions are pure nothrow.

Source

std/math/package.d

@copyrightCopyright The D Language Foundation 2000 - 2011. D implementations of tan, atan, atan2, exp, expm1, exp2, log, log10, log1p, log2, floor, ceil and lrint functions are based on the CEPHES math library, which is Copyright (C) 2001 Stephen L. Moshier <steve@moshier.net> and are incorporated herein by permission of the author. The author reserves the right to distribute this material elsewhere under different copying permissions. These modifications are distributed here under the following terms:@licenseBoost License 1.0.@authorsWalter Bright, Don Clugston, Conversion of CEPHES math library to D by Iain Buclaw and David Nadlinger
math
:
(alias) uom_quantity_logarithmic.log2 = real std.math.exponential.log2(real x) pure nothrow @nogc @safe

Calculates the base-2 logarithm of x: log, 2x

x log2(x) divide by 0? invalid?
0.0 - yes no
<0.0 no yes
+ + no no
log2
,
(alias) uom_quantity_logarithmic.log10 = real std.math.exponential.log10(real x) pure nothrow @nogc @safe

Calculate the base-10 logarithm of x.

x log10(x) divide by 0? invalid?
0.0 - yes no
<0.0 no yes
+ + no no
log10
,
(alias template) uom_quantity_logarithmic.isClose = std.math.operations.isClose(T, U, V = CommonType!(FloatingPointBaseType!T, FloatingPointBaseType!U))(T lhs, U rhs, V maxRelDiff = CommonDefaultFor!(T, U), V maxAbsDiff = 0.0)

Computes whether two values are approximately equal, admitting a maximum relative difference, and a maximum absolute difference.

@paramlhs First item to compare.@paramrhs Second item to compare.@parammaxRelDiff Maximum allowable relative difference. Setting to 0.0 disables this check. Default depends on the type of lhs and rhs: It is approximately half the number of decimal digits of precision of the smaller type.@parammaxAbsDiff Maximum absolute difference. This is mainly usefull for comparing values to zero. Setting to 0.0 disables this check. Defaults to 0.0.@returns

true if the two items are approximately equal under either criterium. It is sufficient, when value satisfies one of the two criteria.

If one item is a range, and the other is a single value, then the result is the logical and-ing of calling isClose on each element of the ranged item against the single item. If both items are ranges, then isClose returns true if and only if the ranges have the same number of elements and if isClose evaluates to true for each pair of elements.

@seeUse feqrel to get the number of equal bits in the mantissa.
isClose
;
/// A plain dimensionless LINEAR ratio — an element of the multiplicative group /// `(ℝ_{>0}, ×)`. This is what a raytracer actually accumulates and scales: /// a gain applied to linear radiance. Its group operation is MULTIPLICATION, /// its identity `Ratio(1.0)`. It carries no dimension exponent (see the graded /// `Quantity` below: it is the `Quantity!0` grade). struct
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
{ double
(field) double uom_quantity_logarithmic.Ratio.factor
factor
;
/// The multiplicative group op: gains compose by `*`, invert by `/`.
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
uom_quantity_logarithmic.Ratio uom_quantity_logarithmic.Ratio.opBinary!"*"(in uom_quantity_logarithmic.Ratio rhs) const pure nothrow @nogc @safe

The multiplicative group op: gains compose by *, invert by /.

opBinary
(string op)(in
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
(parameter) const(uom_quantity_logarithmic.Ratio) rhs
rhs
) const @safe pure nothrow @nogc
if (op == "*" || op == "/") =>
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
(mixin("factor " ~ op ~ " rhs.factor"));
(alias) object.string = string
string
string uom_quantity_logarithmic.Ratio.toString() const @safe
toString
() const @safe
{ import
(package) std
std
.
(module) std.format

This package provides string formatting functionality using printf style format strings.

Submodule Function Name Description
package
format
Converts its arguments according to a format string into a string.

| package | sformat | Converts its arguments according to a format string into a buffer. |

| package | FormatException | Signals a problem while formatting. |

| write | formattedWrite | Converts its arguments according to a format string and writes the result to an output range. |

| write | formatValue | Formats a value of any type according to a format specifier and writes the result to an output range. |

| read | formattedRead | Reads an input range according to a format string and stores the read values into its arguments. |

| read | unformatValue | Reads a value from the given input range and converts it according to a format specifier. |

| spec | FormatSpec | A general handler for format strings. |

| spec | singleSpec | Helper function that returns a FormatSpec for a single format specifier. |

Limitation

This package does not support localization, but adheres to the rounding mode of the floating point unit, if available.

Format Strings

The functions contained in this package use format strings. A format string describes the layout of another string for reading or writing purposes. A format string is composed of normal text interspersed with format specifiers. A format specifier starts with a percentage sign '%', optionally followed by one or more parameters and ends with a format indicator. A format indicator may be a simple format character or a compound indicator.

Format strings are composed according to the following grammar:

FormatString: FormatStringItem FormatString FormatStringItem: Character FormatSpecifier FormatSpecifier: '%' Parameters FormatIndicator

FormatIndicator: FormatCharacter CompoundIndicator FormatCharacter: see remark below CompoundIndicator: '(' FormatString '%)' '(' FormatString '%|' Delimiter '%)' Delimiter empty Character Delimiter

Parameters: Position Flags Width Precision Separator Position: empty Integer '$'** *Integer* **':'** *Integer* **'$' Integer ':' '$'** *Flags*: *empty* *Flag* *Flags* *Flag*: **'-'**|**'+'**|**'&nbsp;'**|**'0'**|**'#'**|**'='** *Width*: *OptionalPositionalInteger* *Precision*: *empty* **'.'** *OptionalPositionalInteger* *Separator*: *empty* **','** *OptionalInteger* **','** *OptionalInteger* **'?'** *OptionalInteger*: *empty* *Integer* **'*'** *OptionalPositionalInteger*: *OptionalInteger* **'*'** *Integer* **'$'

Character '%%' AnyCharacterExceptPercent Integer: NonZeroDigit Digits Digits: empty Digit Digits NonZeroDigit: '1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9' Digit: '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'

Note

FormatCharacter is unspecified. It can be any character that has no other purpose in this grammar, but it is recommended to assign (lower- and uppercase) letters.

Note

The Parameters of a CompoundIndicator are currently limited to a '-' flag.

Format Indicator

The format indicator can either be a single character or an expression surrounded by '%(' and '%)'. It specifies the basic manner in which a value will be formatted and is the minimum requirement to format a value.

The following characters can be used as format characters:

FormatCharacter Semantics
's'
To be formatted in a human readable format.
Can be used with all types.
'c'
To be formatted as a character.
'd'
To be formatted as a signed decimal integer.
'u'
To be formatted as a decimal image of the underlying bit representation.
'b'
To be formatted as a binary image of the underlying bit representation.
'o'
To be formatted as an octal image of the underlying bit representation.
'x' / 'X'
To be formatted as a hexadecimal image of the underlying bit representation.
'e' / 'E'
To be formatted as a real number in decimal scientific notation.
'f' / 'F'
To be formatted as a real number in decimal natural notation.
'g' / 'G'
To be formatted as a real number in decimal short notation.
Depending on the number, a scientific notation or
a natural notation is used.
'a' / 'A'
To be formatted as a real number in hexadecimal scientific notation.
'r'
To be formatted as raw bytes.
The output may not be printable and depends on endianness.

The compound indicator can be used to describe compound types like arrays or structs in more detail. A compound type is enclosed within '%(' and '%)'. The enclosed sub-format string is applied to individual elements. The trailing portion of the sub-format string following the specifier for the element is interpreted as the delimiter, and is therefore omitted following the last element. The '%|' specifier may be used to explicitly indicate the start of the delimiter, so that the preceding portion of the string will be included following the last element.

The format string inside of the compound indicator should contain exactly one format specifier (two in case of associative arrays), which specifies the formatting mode of the elements of the compound type. This format specifier can be a compound indicator itself.

Note

Inside a compound indicator, strings and characters are escaped automatically. To avoid this behavior, use "%-(" instead of "%(".

Flags

There are several flags that affect the outcome of the formatting.

Flag Semantics
'-'
When the formatted result is shorter than the value
given by the width parameter, the output is left
justified. Without the '-' flag, the output remains
right justified.

There are two exceptions where the '-' flag has a different meaning: (1) with 'r' it denotes to use little endian and (2) in case of a compound indicator it means that no special handling of the members is applied. | | '=' | When the formatted result is shorter than the value given by the width parameter, the output is centered. If the central position is not possible it is moved slightly to the right. In this case, if '-' flag is present in addition to the '=' flag, it is moved slightly to the left. | | '+'&nbsp;/&nbsp;*'&nbsp;'* | Applies to numerical values. By default, positive numbers are not formatted to include the + sign. With one of these two flags present, positive numbers are preceded by a plus sign or a space. When both flags are present, a plus sign is used.

In case of 'r', a big endian format is used. | | '0' | Is applied to numerical values that are printed right justified. If the zero flag is present, the space left to the number is filled with zeros instead of spaces. | | '#' | Denotes that an alternative output must be used. This depends on the type to be formatted and the format character used. See the sections below for more information. |

Width, Precision and Separator

The width parameter specifies the minimum width of the result.

The meaning of precision depends on the format indicator. For integers it denotes the minimum number of digits printed, for real numbers it denotes the number of fractional digits and for strings and compound types it denotes the maximum number of elements that are included in the output.

A separator is used for formatting numbers. If it is specified, the output is divided into chunks of three digits, separated by a ','. The number of digits in a chunk can be given explicitly by providing a number or a ''* after the ','.

In all three cases the number of digits can be replaced by a ''*. In this scenario, the next argument is used as the number of digits. If the argument is a negative number, the precision and separator parameters are considered unspecified. For width, the absolute value is used and the '-' flag is set.

The separator can also be followed by a '?'. In that case, an additional argument is used to specify the symbol that should be used to separate the chunks.

Position

By default, the arguments are processed in the provided order. With the position parameter it is possible to address arguments directly. It is also possible to denote a series of arguments with two numbers separated by ':', that are all processed in the same way. The second number can be omitted. In that case the series ends with the last argument.

It's also possible to use positional arguments for width, precision and separator by adding a number and a '$' after the ''*.

Types

This section describes the result of combining types with format characters. It is organized in 2 subsections: a list of general information regarding the formatting of types in the presence of format characters and a table that contains details for every available combination of type and format character.

When formatting types, the following rules apply:

  • If the format character is upper case, the resulting string will be formatted using upper case letters.

  • The default precision for floating point numbers is 6 digits.

  • Rounding of floating point numbers adheres to the rounding mode of the floating point unit, if available.

  • The floating point values NaN and Infinity are formatted as nan and inf, possibly preceded by '+' or '-' sign.

  • Formatting reals is only supported for 64 bit reals and 80 bit reals. All other reals are cast to double before they are formatted. This will cause the result to be inf for very large numbers.

  • Characters and strings formatted with the 's' format character inside of compound types are surrounded by single and double quotes and unprintable characters are escaped. To avoid this, a '-' flag can be specified for the compound specifier (e.g. "%-(%s%)" instead of "%(%s%)" ).

  • Structs, unions, classes and interfaces are formatted by calling a toString method if available. See module std.format.write for more details.

  • Only part of these combinations can be used for reading. See module std.format.read for more detailed information.

This table contains descriptions for every possible combination of type and format character:

<th scope="col" width="20%">Type</th> <th scope="col" width="20%">Format Character</th> Formatted as...
<td rowspan="1">null</td> 's'
null

|<td rowspan="3">bool</td> 's' | false or true |

| 'b', 'd', 'o', 'u', 'x', 'X' | As the integrals 0 or 1 with the same format character.

Please note, that 'o' and 'x' with '#' flag might produce unexpected results due to special handling of the value 0. |

| 'r' | \0 or \1 |

|<td rowspan="4">Integral</td> 's', 'd' | A signed decimal number. The '#' flag is ignored. |

| 'b', 'o', 'u', 'x', 'X' | An unsigned binary, decimal, octal or hexadecimal number.

In case of 'o' and 'x', the '#' flag denotes that the number must be preceded by 0 and 0x, with the exception of the value 0, where this does not apply. For 'b' and 'u' the '#' flag has no effect. |

| 'e', 'E', 'f', 'F', 'g', 'G', 'a', 'A' | As a floating point value with the same specifier.

Default precision is large enough to add all digits of the integral value.

In case of 'a' and 'A', the integral digit can be any hexadecimal digit. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="5">Floating Point</td> 'e', 'E' | Scientific notation: Exactly one integral digit followed by a dot and fractional digits, followed by the exponent. The exponent is formatted as 'e' followed by a '+' or '-' sign, followed by at least two digits.

When there are no fractional digits and the '#' flag is not present, the dot is omitted. |

| 'f', 'F' | Natural notation: Integral digits followed by a dot and fractional digits.

When there are no fractional digits and the '#' flag is not present, the dot is omitted.

Please note: the difference between 'f' and 'F' is only visible for NaN and Infinity. |

| 's', 'g', 'G' | Short notation: If the absolute value is larger than 10 ^^ precision or smaller than 0.0001, the scientific notation is used. If not, the natural notation is applied.

In both cases precision denotes the count of all digits, including the integral digits. Trailing zeros (including a trailing dot) are removed.

If '#' flag is present, trailing zeros are not removed. |

| 'a', 'A' | Hexadecimal scientific notation: 0x followed by 1 (or 0 in case of value zero or denormalized number) followed by a dot, fractional digits in hexadecimal notation and an exponent. The exponent is build by p, followed by a sign and the exponent in decimal notation.

When there are no fractional digits and the '#' flag is not present, the dot is omitted. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="3">Character</td> 's', 'c' | As the character.

Inside of a compound indicator 's' is treated differently: The character is surrounded by single quotes and non printable characters are escaped. This can be avoided by preceding the compound indicator with a '-' flag (e.g. "%-(%s%)"). |

| 'b', 'd', 'o', 'u', 'x', 'X' | As the integral that represents the character. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="3">String</td> 's' | The sequence of characters that form the string.

Inside of a compound indicator the string is surrounded by double quotes and non printable characters are escaped. This can be avoided by preceding the compound indicator with a '-' flag (e.g. "%-(%s%)"). |

| 'r' | The sequence of characters, each formatted with 'r'. |

| compound | As an array of characters. |

|<td rowspan="3">Array</td> 's' | When the elements are characters, the array is formatted as a string. In all other cases the array is surrounded by square brackets and the elements are separated by a comma and a space. If the elements are strings, they are surrounded by double quotes and non printable characters are escaped. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="2">Associative Array</td> 's' | As a sequence of the elements in unpredictable order. The output is surrounded by square brackets. The elements are separated by a comma and a space. The elements are formatted as key:value. |

| compound | As a sequence of the elements in unpredictable order. Each element is formatted according to the specifications given inside of the compound specifier. The first specifier is used for formatting the key and the second specifier is used for formatting the value. The order can be changed with positional arguments. For example "%(%2$s (%1$s), %)" will write the value, followed by the key in parenthesis. |

|<td rowspan="2">Enum</td> 's' | The name of the value. If the name is not available, the base value is used, preceeded by a cast. |

| All, but 's' | Enums can be formatted with all format characters that can be used with the base value. In that case they are formatted like the base value. |

|<td rowspan="3">Input Range</td> 's' | When the elements of the range are characters, they are written like a string. In all other cases, the elements are enclosed by square brackets and separated by a comma and a space. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="1">Struct</td> 's' | When the struct has neither an applicable toString nor is an input range, it is formatted as follows: StructType(field1, field2, ...). |

|<td rowspan="1">Class</td> 's' | When the class has neither an applicable toString nor is an input range, it is formatted as the fully qualified name of the class. |

|<td rowspan="1">Union</td> 's' | When the union has neither an applicable toString nor is an input range, it is formatted as its base name. |

|<td rowspan="2">Pointer</td> 's' | A null pointer is formatted as 'null'. All other pointers are formatted as hexadecimal numbers with the format character 'X'. |

| 'x', 'X' | Formatted as a hexadecimal number. |

|<td rowspan="3">SIMD vector</td> 's' | The array is surrounded by square brackets and the elements are separated by a comma and a space. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="1">Delegate</td> 's', 'r', compound | As the .stringof of this delegate treated as a string.

Please note: The implementation is currently buggy and its use is discouraged. |

Source

std/format/package.d

Examples

Simple use:

// Easiest way is to use `%s` everywhere:
assert(format("I got %s %s for %s euros.", 30, "eggs", 5.27) == "I got 30 eggs for 5.27 euros.");

// Other format characters provide more control:
assert(format("I got %b %(%X%) for %f euros.", 30, "eggs", 5.27) == "I got 11110 65676773 for 5.270000 euros.");

Compound specifiers allow formatting arrays and other compound types:

/*
The trailing end of the sub-format string following the specifier for
each item is interpreted as the array delimiter, and is therefore
omitted following the last array item:
 */
    assert(format("My items are %(%s %).", [1,2,3]) == "My items are 1 2 3.");
    assert(format("My items are %(%s, %).", [1,2,3]) == "My items are 1, 2, 3.");

/*
The "%|" delimiter specifier may be used to indicate where the
delimiter begins, so that the portion of the format string prior to
it will be retained in the last array element:
 */
    assert(format("My items are %(-%s-%|, %).", [1,2,3]) == "My items are -1-, -2-, -3-.");

/*
These compound format specifiers may be nested in the case of a
nested array argument:
 */
    auto mat = [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]];

    assert(format("%(%(%d %) - %)", mat), "1 2 3 - 4 5 6 - 7 8 9");
    assert(format("[%(%(%d %) - %)]", mat), "[1 2 3 - 4 5 6 - 7 8 9]");
    assert(format("[%([%(%d %)]%| - %)]", mat), "[1 2 3] - [4 5 6] - [7 8 9]");

/*
Strings and characters are escaped automatically inside compound
format specifiers. To avoid this behavior, use "%-(" instead of "%(":
 */
    assert(format("My friends are %s.", ["John", "Nancy"]) == `My friends are ["John", "Nancy"].`);
    assert(format("My friends are %(%s, %).", ["John", "Nancy"]) == `My friends are "John", "Nancy".`);
    assert(format("My friends are %-(%s, %).", ["John", "Nancy"]) == `My friends are John, Nancy.`);

Using parameters:

// Flags can be used to influence to outcome:
assert(format("%g != %+#g", 3.14, 3.14) == "3.14 != +3.14000");

// Width and precision help to arrange the formatted result:
assert(format(">%10.2f<", 1234.56789) == ">   1234.57<");

// Numbers can be grouped:
assert(format("%,4d", int.max) == "21,4748,3647");

// It's possible to specify the position of an argument:
assert(format("%3$s %1$s", 3, 17, 5) == "5 3");

Providing parameters as arguments:

// Width as argument
assert(format(">%*s<", 10, "abc") == ">       abc<");

// Precision as argument
assert(format(">%.*f<", 5, 123.2) == ">123.20000<");

// Grouping as argument
assert(format("%,*d", 1, int.max) == "2,1,4,7,4,8,3,6,4,7");

// Grouping separator as argument
assert(format("%,3?d", '_', int.max) == "2_147_483_647");

// All at once
assert(format("%*.*,*?d", 20, 15, 6, '/', int.max) == "   000/002147/483647");
@copyrightCopyright The D Language Foundation 2000-2021.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, and Kenji Hara
format
:
(alias template) format = std.format.format(Char, Args...)(in Char[] fmt, Args args) if (isSomeChar!Char)

Converts its arguments according to a format string into a string.

The second version of format takes the format string as template argument. In this case, it is checked for consistency at compile-time and produces slightly faster code, because the length of the output buffer can be estimated in advance.

Params: fmt = a $(MREF_ALTTEXT format string, std,format) args = a variadic list of arguments to be formatted Char = character type of fmt Args = a variadic list of types of the arguments

Returns: The formatted string.

Throws: A $(LREF FormatException) if formatting did not succeed.

See_Also: $(LREF sformat) for a variant, that tries to avoid garbage collection.

format
;
return
string std.format.format!("\xc3\x97%.6g", const(double))(const(double) __param_0) pure @safe

Examples

The format string can be checked at compile-time:

auto s = format!"%s is %s"("Pi", 3.14);
assert(s == "Pi is 3.14");

// This line doesn't compile, because 3.14 cannot be formatted with %d:
// s = format!"%s is %d"("Pi", 3.14);
format
!"×%.6g"(
(field) double uom_quantity_logarithmic.Ratio.factor
factor
);
} } /// A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. /// One stop doubles exposure. The payload `ev` lives in the ADDITIVE group /// `(ℝ, +)`: composing two exposure adjustments ADDS their stop counts, which /// MULTIPLIES the underlying linear `Ratio`. `Stops` is therefore not a new /// dimension grade — it is the isomorphism `log₂ : (ℝ_{>0}, ×) → (ℝ, +)`, /// meaningful only relative to a reference exposure. struct
(struct) uom_quantity_logarithmic.Stops

A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. One stop doubles exposure. The payload ev lives in the ADDITIVE group (ℝ, +): composing two exposure adjustments ADDS their stop counts, which MULTIPLIES the underlying linear Ratio. Stops is therefore not a new dimension grade — it is the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +), meaningful only relative to a reference exposure.

Stops
{ double
(field) double uom_quantity_logarithmic.Stops.ev
ev
;
/// Compose gains: `+` stacks exposure adjustments, `-` removes one. /// LOG-domain addition ≙ LINEAR-domain multiplication (proven below).
(struct) uom_quantity_logarithmic.Stops

A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. One stop doubles exposure. The payload ev lives in the ADDITIVE group (ℝ, +): composing two exposure adjustments ADDS their stop counts, which MULTIPLIES the underlying linear Ratio. Stops is therefore not a new dimension grade — it is the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +), meaningful only relative to a reference exposure.

Stops
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.opBinary!"+"(in uom_quantity_logarithmic.Stops rhs) const pure nothrow @nogc @safe

Compose gains: + stacks exposure adjustments, - removes one. LOG-domain addition ≙ LINEAR-domain multiplication (proven below).

opBinary
(string op)(in
(struct) uom_quantity_logarithmic.Stops

A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. One stop doubles exposure. The payload ev lives in the ADDITIVE group (ℝ, +): composing two exposure adjustments ADDS their stop counts, which MULTIPLIES the underlying linear Ratio. Stops is therefore not a new dimension grade — it is the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +), meaningful only relative to a reference exposure.

Stops
(parameter) const(uom_quantity_logarithmic.Stops) rhs
rhs
) const @safe pure nothrow @nogc
if (op == "+" || op == "-") =>
(struct) uom_quantity_logarithmic.Stops

A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. One stop doubles exposure. The payload ev lives in the ADDITIVE group (ℝ, +): composing two exposure adjustments ADDS their stop counts, which MULTIPLIES the underlying linear Ratio. Stops is therefore not a new dimension grade — it is the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +), meaningful only relative to a reference exposure.

Stops
(mixin("ev " ~ op ~ " rhs.ev"));
/// Scale the *count* of stops by a plain scalar (e.g. `* 0.5` = half a /// stop). Note there is deliberately no `Stops * Stops`: multiplying two /// logarithms is not a group operation on the exposures (see rejections).
(struct) uom_quantity_logarithmic.Stops

A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. One stop doubles exposure. The payload ev lives in the ADDITIVE group (ℝ, +): composing two exposure adjustments ADDS their stop counts, which MULTIPLIES the underlying linear Ratio. Stops is therefore not a new dimension grade — it is the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +), meaningful only relative to a reference exposure.

Stops
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.opBinary!"*"(in double s) const pure nothrow @nogc @safe

Scale the count of stops by a plain scalar (e.g. * 0.5 = half a stop). Note there is deliberately no Stops * Stops: multiplying two logarithms is not a group operation on the exposures (see rejections).

opBinary
(string op)(in double
(parameter) const(double) s
s
) const @safe pure nothrow @nogc
if (op == "*" || op == "/") =>
(struct) uom_quantity_logarithmic.Stops

A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. One stop doubles exposure. The payload ev lives in the ADDITIVE group (ℝ, +): composing two exposure adjustments ADDS their stop counts, which MULTIPLIES the underlying linear Ratio. Stops is therefore not a new dimension grade — it is the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +), meaningful only relative to a reference exposure.

Stops
(mixin("ev " ~ op ~ " s"));
/// Bridge to the linear domain: `2^ev`. This is the isomorphism's inverse /// and is NONLINEAR in `ev` — the root of the vector nonlinearity below.
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
uom_quantity_logarithmic.Ratio uom_quantity_logarithmic.Stops.toLinear() const pure nothrow @nogc @safe

Bridge to the linear domain: 2^ev. This is the isomorphism's inverse and is NONLINEAR in ev — the root of the vector nonlinearity below.

toLinear
() const @safe pure nothrow @nogc
=>
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
(2.0 ^^
(field) double uom_quantity_logarithmic.Stops.ev
ev
);
/// Bridge from a linear ratio: `log₂(factor)`. Defined only for a positive /// ratio — logarithms exist only on the positive multiplicative group, /// which is *why* a log unit needs a reference to be meaningful. static
(struct) uom_quantity_logarithmic.Stops

A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. One stop doubles exposure. The payload ev lives in the ADDITIVE group (ℝ, +): composing two exposure adjustments ADDS their stop counts, which MULTIPLIES the underlying linear Ratio. Stops is therefore not a new dimension grade — it is the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +), meaningful only relative to a reference exposure.

Stops
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.fromLinear(in uom_quantity_logarithmic.Ratio r) pure nothrow @nogc @safe

Bridge from a linear ratio: log₂(factor). Defined only for a positive ratio — logarithms exist only on the positive multiplicative group, which is why a log unit needs a reference to be meaningful.

fromLinear
(in
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
(parameter) const(uom_quantity_logarithmic.Ratio) r
r
) @safe pure nothrow @nogc
in (
(parameter) const(uom_quantity_logarithmic.Ratio) r
r
.
(field) double uom_quantity_logarithmic.Ratio.factor
factor
> 0, "a logarithmic stop is defined only for a positive ratio")
=>
(struct) uom_quantity_logarithmic.Stops

A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. One stop doubles exposure. The payload ev lives in the ADDITIVE group (ℝ, +): composing two exposure adjustments ADDS their stop counts, which MULTIPLIES the underlying linear Ratio. Stops is therefore not a new dimension grade — it is the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +), meaningful only relative to a reference exposure.

Stops
(
double std.math.exponential.log2(double x) pure nothrow @nogc @safe

Calculates the base-2 logarithm of x: log, 2x

x log2(x) divide by 0? invalid?
0.0 - yes no
<0.0 no yes
+ + no no
log2
(
(parameter) const(uom_quantity_logarithmic.Ratio) r
r
.
(field) double uom_quantity_logarithmic.Ratio.factor
factor
));
(alias) object.string = string
string
string uom_quantity_logarithmic.Stops.toString() const @safe
toString
() const @safe
{ import
(package) std
std
.
(module) std.format

This package provides string formatting functionality using printf style format strings.

Submodule Function Name Description
package
format
Converts its arguments according to a format string into a string.

| package | sformat | Converts its arguments according to a format string into a buffer. |

| package | FormatException | Signals a problem while formatting. |

| write | formattedWrite | Converts its arguments according to a format string and writes the result to an output range. |

| write | formatValue | Formats a value of any type according to a format specifier and writes the result to an output range. |

| read | formattedRead | Reads an input range according to a format string and stores the read values into its arguments. |

| read | unformatValue | Reads a value from the given input range and converts it according to a format specifier. |

| spec | FormatSpec | A general handler for format strings. |

| spec | singleSpec | Helper function that returns a FormatSpec for a single format specifier. |

Limitation

This package does not support localization, but adheres to the rounding mode of the floating point unit, if available.

Format Strings

The functions contained in this package use format strings. A format string describes the layout of another string for reading or writing purposes. A format string is composed of normal text interspersed with format specifiers. A format specifier starts with a percentage sign '%', optionally followed by one or more parameters and ends with a format indicator. A format indicator may be a simple format character or a compound indicator.

Format strings are composed according to the following grammar:

FormatString: FormatStringItem FormatString FormatStringItem: Character FormatSpecifier FormatSpecifier: '%' Parameters FormatIndicator

FormatIndicator: FormatCharacter CompoundIndicator FormatCharacter: see remark below CompoundIndicator: '(' FormatString '%)' '(' FormatString '%|' Delimiter '%)' Delimiter empty Character Delimiter

Parameters: Position Flags Width Precision Separator Position: empty Integer '$'** *Integer* **':'** *Integer* **'$' Integer ':' '$'** *Flags*: *empty* *Flag* *Flags* *Flag*: **'-'**|**'+'**|**'&nbsp;'**|**'0'**|**'#'**|**'='** *Width*: *OptionalPositionalInteger* *Precision*: *empty* **'.'** *OptionalPositionalInteger* *Separator*: *empty* **','** *OptionalInteger* **','** *OptionalInteger* **'?'** *OptionalInteger*: *empty* *Integer* **'*'** *OptionalPositionalInteger*: *OptionalInteger* **'*'** *Integer* **'$'

Character '%%' AnyCharacterExceptPercent Integer: NonZeroDigit Digits Digits: empty Digit Digits NonZeroDigit: '1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9' Digit: '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'

Note

FormatCharacter is unspecified. It can be any character that has no other purpose in this grammar, but it is recommended to assign (lower- and uppercase) letters.

Note

The Parameters of a CompoundIndicator are currently limited to a '-' flag.

Format Indicator

The format indicator can either be a single character or an expression surrounded by '%(' and '%)'. It specifies the basic manner in which a value will be formatted and is the minimum requirement to format a value.

The following characters can be used as format characters:

FormatCharacter Semantics
's'
To be formatted in a human readable format.
Can be used with all types.
'c'
To be formatted as a character.
'd'
To be formatted as a signed decimal integer.
'u'
To be formatted as a decimal image of the underlying bit representation.
'b'
To be formatted as a binary image of the underlying bit representation.
'o'
To be formatted as an octal image of the underlying bit representation.
'x' / 'X'
To be formatted as a hexadecimal image of the underlying bit representation.
'e' / 'E'
To be formatted as a real number in decimal scientific notation.
'f' / 'F'
To be formatted as a real number in decimal natural notation.
'g' / 'G'
To be formatted as a real number in decimal short notation.
Depending on the number, a scientific notation or
a natural notation is used.
'a' / 'A'
To be formatted as a real number in hexadecimal scientific notation.
'r'
To be formatted as raw bytes.
The output may not be printable and depends on endianness.

The compound indicator can be used to describe compound types like arrays or structs in more detail. A compound type is enclosed within '%(' and '%)'. The enclosed sub-format string is applied to individual elements. The trailing portion of the sub-format string following the specifier for the element is interpreted as the delimiter, and is therefore omitted following the last element. The '%|' specifier may be used to explicitly indicate the start of the delimiter, so that the preceding portion of the string will be included following the last element.

The format string inside of the compound indicator should contain exactly one format specifier (two in case of associative arrays), which specifies the formatting mode of the elements of the compound type. This format specifier can be a compound indicator itself.

Note

Inside a compound indicator, strings and characters are escaped automatically. To avoid this behavior, use "%-(" instead of "%(".

Flags

There are several flags that affect the outcome of the formatting.

Flag Semantics
'-'
When the formatted result is shorter than the value
given by the width parameter, the output is left
justified. Without the '-' flag, the output remains
right justified.

There are two exceptions where the '-' flag has a different meaning: (1) with 'r' it denotes to use little endian and (2) in case of a compound indicator it means that no special handling of the members is applied. | | '=' | When the formatted result is shorter than the value given by the width parameter, the output is centered. If the central position is not possible it is moved slightly to the right. In this case, if '-' flag is present in addition to the '=' flag, it is moved slightly to the left. | | '+'&nbsp;/&nbsp;*'&nbsp;'* | Applies to numerical values. By default, positive numbers are not formatted to include the + sign. With one of these two flags present, positive numbers are preceded by a plus sign or a space. When both flags are present, a plus sign is used.

In case of 'r', a big endian format is used. | | '0' | Is applied to numerical values that are printed right justified. If the zero flag is present, the space left to the number is filled with zeros instead of spaces. | | '#' | Denotes that an alternative output must be used. This depends on the type to be formatted and the format character used. See the sections below for more information. |

Width, Precision and Separator

The width parameter specifies the minimum width of the result.

The meaning of precision depends on the format indicator. For integers it denotes the minimum number of digits printed, for real numbers it denotes the number of fractional digits and for strings and compound types it denotes the maximum number of elements that are included in the output.

A separator is used for formatting numbers. If it is specified, the output is divided into chunks of three digits, separated by a ','. The number of digits in a chunk can be given explicitly by providing a number or a ''* after the ','.

In all three cases the number of digits can be replaced by a ''*. In this scenario, the next argument is used as the number of digits. If the argument is a negative number, the precision and separator parameters are considered unspecified. For width, the absolute value is used and the '-' flag is set.

The separator can also be followed by a '?'. In that case, an additional argument is used to specify the symbol that should be used to separate the chunks.

Position

By default, the arguments are processed in the provided order. With the position parameter it is possible to address arguments directly. It is also possible to denote a series of arguments with two numbers separated by ':', that are all processed in the same way. The second number can be omitted. In that case the series ends with the last argument.

It's also possible to use positional arguments for width, precision and separator by adding a number and a '$' after the ''*.

Types

This section describes the result of combining types with format characters. It is organized in 2 subsections: a list of general information regarding the formatting of types in the presence of format characters and a table that contains details for every available combination of type and format character.

When formatting types, the following rules apply:

  • If the format character is upper case, the resulting string will be formatted using upper case letters.

  • The default precision for floating point numbers is 6 digits.

  • Rounding of floating point numbers adheres to the rounding mode of the floating point unit, if available.

  • The floating point values NaN and Infinity are formatted as nan and inf, possibly preceded by '+' or '-' sign.

  • Formatting reals is only supported for 64 bit reals and 80 bit reals. All other reals are cast to double before they are formatted. This will cause the result to be inf for very large numbers.

  • Characters and strings formatted with the 's' format character inside of compound types are surrounded by single and double quotes and unprintable characters are escaped. To avoid this, a '-' flag can be specified for the compound specifier (e.g. "%-(%s%)" instead of "%(%s%)" ).

  • Structs, unions, classes and interfaces are formatted by calling a toString method if available. See module std.format.write for more details.

  • Only part of these combinations can be used for reading. See module std.format.read for more detailed information.

This table contains descriptions for every possible combination of type and format character:

<th scope="col" width="20%">Type</th> <th scope="col" width="20%">Format Character</th> Formatted as...
<td rowspan="1">null</td> 's'
null

|<td rowspan="3">bool</td> 's' | false or true |

| 'b', 'd', 'o', 'u', 'x', 'X' | As the integrals 0 or 1 with the same format character.

Please note, that 'o' and 'x' with '#' flag might produce unexpected results due to special handling of the value 0. |

| 'r' | \0 or \1 |

|<td rowspan="4">Integral</td> 's', 'd' | A signed decimal number. The '#' flag is ignored. |

| 'b', 'o', 'u', 'x', 'X' | An unsigned binary, decimal, octal or hexadecimal number.

In case of 'o' and 'x', the '#' flag denotes that the number must be preceded by 0 and 0x, with the exception of the value 0, where this does not apply. For 'b' and 'u' the '#' flag has no effect. |

| 'e', 'E', 'f', 'F', 'g', 'G', 'a', 'A' | As a floating point value with the same specifier.

Default precision is large enough to add all digits of the integral value.

In case of 'a' and 'A', the integral digit can be any hexadecimal digit. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="5">Floating Point</td> 'e', 'E' | Scientific notation: Exactly one integral digit followed by a dot and fractional digits, followed by the exponent. The exponent is formatted as 'e' followed by a '+' or '-' sign, followed by at least two digits.

When there are no fractional digits and the '#' flag is not present, the dot is omitted. |

| 'f', 'F' | Natural notation: Integral digits followed by a dot and fractional digits.

When there are no fractional digits and the '#' flag is not present, the dot is omitted.

Please note: the difference between 'f' and 'F' is only visible for NaN and Infinity. |

| 's', 'g', 'G' | Short notation: If the absolute value is larger than 10 ^^ precision or smaller than 0.0001, the scientific notation is used. If not, the natural notation is applied.

In both cases precision denotes the count of all digits, including the integral digits. Trailing zeros (including a trailing dot) are removed.

If '#' flag is present, trailing zeros are not removed. |

| 'a', 'A' | Hexadecimal scientific notation: 0x followed by 1 (or 0 in case of value zero or denormalized number) followed by a dot, fractional digits in hexadecimal notation and an exponent. The exponent is build by p, followed by a sign and the exponent in decimal notation.

When there are no fractional digits and the '#' flag is not present, the dot is omitted. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="3">Character</td> 's', 'c' | As the character.

Inside of a compound indicator 's' is treated differently: The character is surrounded by single quotes and non printable characters are escaped. This can be avoided by preceding the compound indicator with a '-' flag (e.g. "%-(%s%)"). |

| 'b', 'd', 'o', 'u', 'x', 'X' | As the integral that represents the character. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="3">String</td> 's' | The sequence of characters that form the string.

Inside of a compound indicator the string is surrounded by double quotes and non printable characters are escaped. This can be avoided by preceding the compound indicator with a '-' flag (e.g. "%-(%s%)"). |

| 'r' | The sequence of characters, each formatted with 'r'. |

| compound | As an array of characters. |

|<td rowspan="3">Array</td> 's' | When the elements are characters, the array is formatted as a string. In all other cases the array is surrounded by square brackets and the elements are separated by a comma and a space. If the elements are strings, they are surrounded by double quotes and non printable characters are escaped. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="2">Associative Array</td> 's' | As a sequence of the elements in unpredictable order. The output is surrounded by square brackets. The elements are separated by a comma and a space. The elements are formatted as key:value. |

| compound | As a sequence of the elements in unpredictable order. Each element is formatted according to the specifications given inside of the compound specifier. The first specifier is used for formatting the key and the second specifier is used for formatting the value. The order can be changed with positional arguments. For example "%(%2$s (%1$s), %)" will write the value, followed by the key in parenthesis. |

|<td rowspan="2">Enum</td> 's' | The name of the value. If the name is not available, the base value is used, preceeded by a cast. |

| All, but 's' | Enums can be formatted with all format characters that can be used with the base value. In that case they are formatted like the base value. |

|<td rowspan="3">Input Range</td> 's' | When the elements of the range are characters, they are written like a string. In all other cases, the elements are enclosed by square brackets and separated by a comma and a space. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="1">Struct</td> 's' | When the struct has neither an applicable toString nor is an input range, it is formatted as follows: StructType(field1, field2, ...). |

|<td rowspan="1">Class</td> 's' | When the class has neither an applicable toString nor is an input range, it is formatted as the fully qualified name of the class. |

|<td rowspan="1">Union</td> 's' | When the union has neither an applicable toString nor is an input range, it is formatted as its base name. |

|<td rowspan="2">Pointer</td> 's' | A null pointer is formatted as 'null'. All other pointers are formatted as hexadecimal numbers with the format character 'X'. |

| 'x', 'X' | Formatted as a hexadecimal number. |

|<td rowspan="3">SIMD vector</td> 's' | The array is surrounded by square brackets and the elements are separated by a comma and a space. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="1">Delegate</td> 's', 'r', compound | As the .stringof of this delegate treated as a string.

Please note: The implementation is currently buggy and its use is discouraged. |

Source

std/format/package.d

Examples

Simple use:

// Easiest way is to use `%s` everywhere:
assert(format("I got %s %s for %s euros.", 30, "eggs", 5.27) == "I got 30 eggs for 5.27 euros.");

// Other format characters provide more control:
assert(format("I got %b %(%X%) for %f euros.", 30, "eggs", 5.27) == "I got 11110 65676773 for 5.270000 euros.");

Compound specifiers allow formatting arrays and other compound types:

/*
The trailing end of the sub-format string following the specifier for
each item is interpreted as the array delimiter, and is therefore
omitted following the last array item:
 */
    assert(format("My items are %(%s %).", [1,2,3]) == "My items are 1 2 3.");
    assert(format("My items are %(%s, %).", [1,2,3]) == "My items are 1, 2, 3.");

/*
The "%|" delimiter specifier may be used to indicate where the
delimiter begins, so that the portion of the format string prior to
it will be retained in the last array element:
 */
    assert(format("My items are %(-%s-%|, %).", [1,2,3]) == "My items are -1-, -2-, -3-.");

/*
These compound format specifiers may be nested in the case of a
nested array argument:
 */
    auto mat = [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]];

    assert(format("%(%(%d %) - %)", mat), "1 2 3 - 4 5 6 - 7 8 9");
    assert(format("[%(%(%d %) - %)]", mat), "[1 2 3 - 4 5 6 - 7 8 9]");
    assert(format("[%([%(%d %)]%| - %)]", mat), "[1 2 3] - [4 5 6] - [7 8 9]");

/*
Strings and characters are escaped automatically inside compound
format specifiers. To avoid this behavior, use "%-(" instead of "%(":
 */
    assert(format("My friends are %s.", ["John", "Nancy"]) == `My friends are ["John", "Nancy"].`);
    assert(format("My friends are %(%s, %).", ["John", "Nancy"]) == `My friends are "John", "Nancy".`);
    assert(format("My friends are %-(%s, %).", ["John", "Nancy"]) == `My friends are John, Nancy.`);

Using parameters:

// Flags can be used to influence to outcome:
assert(format("%g != %+#g", 3.14, 3.14) == "3.14 != +3.14000");

// Width and precision help to arrange the formatted result:
assert(format(">%10.2f<", 1234.56789) == ">   1234.57<");

// Numbers can be grouped:
assert(format("%,4d", int.max) == "21,4748,3647");

// It's possible to specify the position of an argument:
assert(format("%3$s %1$s", 3, 17, 5) == "5 3");

Providing parameters as arguments:

// Width as argument
assert(format(">%*s<", 10, "abc") == ">       abc<");

// Precision as argument
assert(format(">%.*f<", 5, 123.2) == ">123.20000<");

// Grouping as argument
assert(format("%,*d", 1, int.max) == "2,1,4,7,4,8,3,6,4,7");

// Grouping separator as argument
assert(format("%,3?d", '_', int.max) == "2_147_483_647");

// All at once
assert(format("%*.*,*?d", 20, 15, 6, '/', int.max) == "   000/002147/483647");
@copyrightCopyright The D Language Foundation 2000-2021.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, and Kenji Hara
format
:
(alias template) format = std.format.format(Char, Args...)(in Char[] fmt, Args args) if (isSomeChar!Char)

Converts its arguments according to a format string into a string.

The second version of format takes the format string as template argument. In this case, it is checked for consistency at compile-time and produces slightly faster code, because the length of the output buffer can be estimated in advance.

Params: fmt = a $(MREF_ALTTEXT format string, std,format) args = a variadic list of arguments to be formatted Char = character type of fmt Args = a variadic list of types of the arguments

Returns: The formatted string.

Throws: A $(LREF FormatException) if formatting did not succeed.

See_Also: $(LREF sformat) for a variant, that tries to avoid garbage collection.

format
;
return
string std.format.format!("%+.6g EV", const(double))(const(double) __param_0) pure @safe

Examples

The format string can be checked at compile-time:

auto s = format!"%s is %s"("Pi", 3.14);
assert(s == "Pi is 3.14");

// This line doesn't compile, because 3.14 cannot be formatted with %d:
// s = format!"%s is %d"("Pi", 3.14);
format
!"%+.6g EV"(
(field) double uom_quantity_logarithmic.Stops.ev
ev
);
} } /// A second logarithmic quantity, on a different base and reference: power /// decibels, `dB = 10·log₁₀(P/P_ref)`, so `+3 dB ≈ ×2` power. It shares Stops' /// structure (add-in-log ≙ multiply-in-linear) but with base 10 and factor 10. /// That two log units with *different* constants share one algebra underscores /// the point: the log unit carries no dimension of its own — it is the /// reference and base that give it meaning, not a grade in the dimension group. struct
(struct) uom_quantity_logarithmic.Decibels

A second logarithmic quantity, on a different base and reference: power decibels, dB = 10·log₁₀(P/P_ref), so +3 dB ≈ ×2 power. It shares Stops' structure (add-in-log ≙ multiply-in-linear) but with base 10 and factor 10. That two log units with different constants share one algebra underscores the point: the log unit carries no dimension of its own — it is the reference and base that give it meaning, not a grade in the dimension group.

Decibels
{ double
(field) double uom_quantity_logarithmic.Decibels.db
db
;
(struct) uom_quantity_logarithmic.Decibels

A second logarithmic quantity, on a different base and reference: power decibels, dB = 10·log₁₀(P/P_ref), so +3 dB ≈ ×2 power. It shares Stops' structure (add-in-log ≙ multiply-in-linear) but with base 10 and factor 10. That two log units with different constants share one algebra underscores the point: the log unit carries no dimension of its own — it is the reference and base that give it meaning, not a grade in the dimension group.

Decibels
uom_quantity_logarithmic.Decibels uom_quantity_logarithmic.Decibels.opBinary!"+"(in uom_quantity_logarithmic.Decibels rhs) const pure nothrow @nogc @safe
opBinary
(string op)(in
(struct) uom_quantity_logarithmic.Decibels

A second logarithmic quantity, on a different base and reference: power decibels, dB = 10·log₁₀(P/P_ref), so +3 dB ≈ ×2 power. It shares Stops' structure (add-in-log ≙ multiply-in-linear) but with base 10 and factor 10. That two log units with different constants share one algebra underscores the point: the log unit carries no dimension of its own — it is the reference and base that give it meaning, not a grade in the dimension group.

Decibels
(parameter) const(uom_quantity_logarithmic.Decibels) rhs
rhs
) const @safe pure nothrow @nogc
if (op == "+" || op == "-") =>
(struct) uom_quantity_logarithmic.Decibels

A second logarithmic quantity, on a different base and reference: power decibels, dB = 10·log₁₀(P/P_ref), so +3 dB ≈ ×2 power. It shares Stops' structure (add-in-log ≙ multiply-in-linear) but with base 10 and factor 10. That two log units with different constants share one algebra underscores the point: the log unit carries no dimension of its own — it is the reference and base that give it meaning, not a grade in the dimension group.

Decibels
(mixin("db " ~ op ~ " rhs.db"));
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
uom_quantity_logarithmic.Ratio uom_quantity_logarithmic.Decibels.toLinear() const pure nothrow @nogc @safe
toLinear
() const @safe pure nothrow @nogc
=>
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
(10.0 ^^ (
(field) double uom_quantity_logarithmic.Decibels.db
db
/ 10.0));
static
(struct) uom_quantity_logarithmic.Decibels

A second logarithmic quantity, on a different base and reference: power decibels, dB = 10·log₁₀(P/P_ref), so +3 dB ≈ ×2 power. It shares Stops' structure (add-in-log ≙ multiply-in-linear) but with base 10 and factor 10. That two log units with different constants share one algebra underscores the point: the log unit carries no dimension of its own — it is the reference and base that give it meaning, not a grade in the dimension group.

Decibels
uom_quantity_logarithmic.Decibels uom_quantity_logarithmic.Decibels.fromLinear(in uom_quantity_logarithmic.Ratio r) pure nothrow @nogc @safe
fromLinear
(in
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
(parameter) const(uom_quantity_logarithmic.Ratio) r
r
) @safe pure nothrow @nogc
in (
(parameter) const(uom_quantity_logarithmic.Ratio) r
r
.
(field) double uom_quantity_logarithmic.Ratio.factor
factor
> 0, "decibels are defined only for a positive power ratio")
=>
(struct) uom_quantity_logarithmic.Decibels

A second logarithmic quantity, on a different base and reference: power decibels, dB = 10·log₁₀(P/P_ref), so +3 dB ≈ ×2 power. It shares Stops' structure (add-in-log ≙ multiply-in-linear) but with base 10 and factor 10. That two log units with different constants share one algebra underscores the point: the log unit carries no dimension of its own — it is the reference and base that give it meaning, not a grade in the dimension group.

Decibels
(10.0 *
double std.math.exponential.log10(double x) pure nothrow @nogc @safe

Calculate the base-10 logarithm of x.

x log10(x) divide by 0? invalid?
0.0 - yes no
<0.0 no yes
+ + no no
log10
(
(parameter) const(uom_quantity_logarithmic.Ratio) r
r
.
(field) double uom_quantity_logarithmic.Ratio.factor
factor
));
(alias) object.string = string
string
string uom_quantity_logarithmic.Decibels.toString() const @safe
toString
() const @safe
{ import
(package) std
std
.
(module) std.format

This package provides string formatting functionality using printf style format strings.

Submodule Function Name Description
package
format
Converts its arguments according to a format string into a string.

| package | sformat | Converts its arguments according to a format string into a buffer. |

| package | FormatException | Signals a problem while formatting. |

| write | formattedWrite | Converts its arguments according to a format string and writes the result to an output range. |

| write | formatValue | Formats a value of any type according to a format specifier and writes the result to an output range. |

| read | formattedRead | Reads an input range according to a format string and stores the read values into its arguments. |

| read | unformatValue | Reads a value from the given input range and converts it according to a format specifier. |

| spec | FormatSpec | A general handler for format strings. |

| spec | singleSpec | Helper function that returns a FormatSpec for a single format specifier. |

Limitation

This package does not support localization, but adheres to the rounding mode of the floating point unit, if available.

Format Strings

The functions contained in this package use format strings. A format string describes the layout of another string for reading or writing purposes. A format string is composed of normal text interspersed with format specifiers. A format specifier starts with a percentage sign '%', optionally followed by one or more parameters and ends with a format indicator. A format indicator may be a simple format character or a compound indicator.

Format strings are composed according to the following grammar:

FormatString: FormatStringItem FormatString FormatStringItem: Character FormatSpecifier FormatSpecifier: '%' Parameters FormatIndicator

FormatIndicator: FormatCharacter CompoundIndicator FormatCharacter: see remark below CompoundIndicator: '(' FormatString '%)' '(' FormatString '%|' Delimiter '%)' Delimiter empty Character Delimiter

Parameters: Position Flags Width Precision Separator Position: empty Integer '$'** *Integer* **':'** *Integer* **'$' Integer ':' '$'** *Flags*: *empty* *Flag* *Flags* *Flag*: **'-'**|**'+'**|**'&nbsp;'**|**'0'**|**'#'**|**'='** *Width*: *OptionalPositionalInteger* *Precision*: *empty* **'.'** *OptionalPositionalInteger* *Separator*: *empty* **','** *OptionalInteger* **','** *OptionalInteger* **'?'** *OptionalInteger*: *empty* *Integer* **'*'** *OptionalPositionalInteger*: *OptionalInteger* **'*'** *Integer* **'$'

Character '%%' AnyCharacterExceptPercent Integer: NonZeroDigit Digits Digits: empty Digit Digits NonZeroDigit: '1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9' Digit: '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'

Note

FormatCharacter is unspecified. It can be any character that has no other purpose in this grammar, but it is recommended to assign (lower- and uppercase) letters.

Note

The Parameters of a CompoundIndicator are currently limited to a '-' flag.

Format Indicator

The format indicator can either be a single character or an expression surrounded by '%(' and '%)'. It specifies the basic manner in which a value will be formatted and is the minimum requirement to format a value.

The following characters can be used as format characters:

FormatCharacter Semantics
's'
To be formatted in a human readable format.
Can be used with all types.
'c'
To be formatted as a character.
'd'
To be formatted as a signed decimal integer.
'u'
To be formatted as a decimal image of the underlying bit representation.
'b'
To be formatted as a binary image of the underlying bit representation.
'o'
To be formatted as an octal image of the underlying bit representation.
'x' / 'X'
To be formatted as a hexadecimal image of the underlying bit representation.
'e' / 'E'
To be formatted as a real number in decimal scientific notation.
'f' / 'F'
To be formatted as a real number in decimal natural notation.
'g' / 'G'
To be formatted as a real number in decimal short notation.
Depending on the number, a scientific notation or
a natural notation is used.
'a' / 'A'
To be formatted as a real number in hexadecimal scientific notation.
'r'
To be formatted as raw bytes.
The output may not be printable and depends on endianness.

The compound indicator can be used to describe compound types like arrays or structs in more detail. A compound type is enclosed within '%(' and '%)'. The enclosed sub-format string is applied to individual elements. The trailing portion of the sub-format string following the specifier for the element is interpreted as the delimiter, and is therefore omitted following the last element. The '%|' specifier may be used to explicitly indicate the start of the delimiter, so that the preceding portion of the string will be included following the last element.

The format string inside of the compound indicator should contain exactly one format specifier (two in case of associative arrays), which specifies the formatting mode of the elements of the compound type. This format specifier can be a compound indicator itself.

Note

Inside a compound indicator, strings and characters are escaped automatically. To avoid this behavior, use "%-(" instead of "%(".

Flags

There are several flags that affect the outcome of the formatting.

Flag Semantics
'-'
When the formatted result is shorter than the value
given by the width parameter, the output is left
justified. Without the '-' flag, the output remains
right justified.

There are two exceptions where the '-' flag has a different meaning: (1) with 'r' it denotes to use little endian and (2) in case of a compound indicator it means that no special handling of the members is applied. | | '=' | When the formatted result is shorter than the value given by the width parameter, the output is centered. If the central position is not possible it is moved slightly to the right. In this case, if '-' flag is present in addition to the '=' flag, it is moved slightly to the left. | | '+'&nbsp;/&nbsp;*'&nbsp;'* | Applies to numerical values. By default, positive numbers are not formatted to include the + sign. With one of these two flags present, positive numbers are preceded by a plus sign or a space. When both flags are present, a plus sign is used.

In case of 'r', a big endian format is used. | | '0' | Is applied to numerical values that are printed right justified. If the zero flag is present, the space left to the number is filled with zeros instead of spaces. | | '#' | Denotes that an alternative output must be used. This depends on the type to be formatted and the format character used. See the sections below for more information. |

Width, Precision and Separator

The width parameter specifies the minimum width of the result.

The meaning of precision depends on the format indicator. For integers it denotes the minimum number of digits printed, for real numbers it denotes the number of fractional digits and for strings and compound types it denotes the maximum number of elements that are included in the output.

A separator is used for formatting numbers. If it is specified, the output is divided into chunks of three digits, separated by a ','. The number of digits in a chunk can be given explicitly by providing a number or a ''* after the ','.

In all three cases the number of digits can be replaced by a ''*. In this scenario, the next argument is used as the number of digits. If the argument is a negative number, the precision and separator parameters are considered unspecified. For width, the absolute value is used and the '-' flag is set.

The separator can also be followed by a '?'. In that case, an additional argument is used to specify the symbol that should be used to separate the chunks.

Position

By default, the arguments are processed in the provided order. With the position parameter it is possible to address arguments directly. It is also possible to denote a series of arguments with two numbers separated by ':', that are all processed in the same way. The second number can be omitted. In that case the series ends with the last argument.

It's also possible to use positional arguments for width, precision and separator by adding a number and a '$' after the ''*.

Types

This section describes the result of combining types with format characters. It is organized in 2 subsections: a list of general information regarding the formatting of types in the presence of format characters and a table that contains details for every available combination of type and format character.

When formatting types, the following rules apply:

  • If the format character is upper case, the resulting string will be formatted using upper case letters.

  • The default precision for floating point numbers is 6 digits.

  • Rounding of floating point numbers adheres to the rounding mode of the floating point unit, if available.

  • The floating point values NaN and Infinity are formatted as nan and inf, possibly preceded by '+' or '-' sign.

  • Formatting reals is only supported for 64 bit reals and 80 bit reals. All other reals are cast to double before they are formatted. This will cause the result to be inf for very large numbers.

  • Characters and strings formatted with the 's' format character inside of compound types are surrounded by single and double quotes and unprintable characters are escaped. To avoid this, a '-' flag can be specified for the compound specifier (e.g. "%-(%s%)" instead of "%(%s%)" ).

  • Structs, unions, classes and interfaces are formatted by calling a toString method if available. See module std.format.write for more details.

  • Only part of these combinations can be used for reading. See module std.format.read for more detailed information.

This table contains descriptions for every possible combination of type and format character:

<th scope="col" width="20%">Type</th> <th scope="col" width="20%">Format Character</th> Formatted as...
<td rowspan="1">null</td> 's'
null

|<td rowspan="3">bool</td> 's' | false or true |

| 'b', 'd', 'o', 'u', 'x', 'X' | As the integrals 0 or 1 with the same format character.

Please note, that 'o' and 'x' with '#' flag might produce unexpected results due to special handling of the value 0. |

| 'r' | \0 or \1 |

|<td rowspan="4">Integral</td> 's', 'd' | A signed decimal number. The '#' flag is ignored. |

| 'b', 'o', 'u', 'x', 'X' | An unsigned binary, decimal, octal or hexadecimal number.

In case of 'o' and 'x', the '#' flag denotes that the number must be preceded by 0 and 0x, with the exception of the value 0, where this does not apply. For 'b' and 'u' the '#' flag has no effect. |

| 'e', 'E', 'f', 'F', 'g', 'G', 'a', 'A' | As a floating point value with the same specifier.

Default precision is large enough to add all digits of the integral value.

In case of 'a' and 'A', the integral digit can be any hexadecimal digit. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="5">Floating Point</td> 'e', 'E' | Scientific notation: Exactly one integral digit followed by a dot and fractional digits, followed by the exponent. The exponent is formatted as 'e' followed by a '+' or '-' sign, followed by at least two digits.

When there are no fractional digits and the '#' flag is not present, the dot is omitted. |

| 'f', 'F' | Natural notation: Integral digits followed by a dot and fractional digits.

When there are no fractional digits and the '#' flag is not present, the dot is omitted.

Please note: the difference between 'f' and 'F' is only visible for NaN and Infinity. |

| 's', 'g', 'G' | Short notation: If the absolute value is larger than 10 ^^ precision or smaller than 0.0001, the scientific notation is used. If not, the natural notation is applied.

In both cases precision denotes the count of all digits, including the integral digits. Trailing zeros (including a trailing dot) are removed.

If '#' flag is present, trailing zeros are not removed. |

| 'a', 'A' | Hexadecimal scientific notation: 0x followed by 1 (or 0 in case of value zero or denormalized number) followed by a dot, fractional digits in hexadecimal notation and an exponent. The exponent is build by p, followed by a sign and the exponent in decimal notation.

When there are no fractional digits and the '#' flag is not present, the dot is omitted. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="3">Character</td> 's', 'c' | As the character.

Inside of a compound indicator 's' is treated differently: The character is surrounded by single quotes and non printable characters are escaped. This can be avoided by preceding the compound indicator with a '-' flag (e.g. "%-(%s%)"). |

| 'b', 'd', 'o', 'u', 'x', 'X' | As the integral that represents the character. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="3">String</td> 's' | The sequence of characters that form the string.

Inside of a compound indicator the string is surrounded by double quotes and non printable characters are escaped. This can be avoided by preceding the compound indicator with a '-' flag (e.g. "%-(%s%)"). |

| 'r' | The sequence of characters, each formatted with 'r'. |

| compound | As an array of characters. |

|<td rowspan="3">Array</td> 's' | When the elements are characters, the array is formatted as a string. In all other cases the array is surrounded by square brackets and the elements are separated by a comma and a space. If the elements are strings, they are surrounded by double quotes and non printable characters are escaped. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="2">Associative Array</td> 's' | As a sequence of the elements in unpredictable order. The output is surrounded by square brackets. The elements are separated by a comma and a space. The elements are formatted as key:value. |

| compound | As a sequence of the elements in unpredictable order. Each element is formatted according to the specifications given inside of the compound specifier. The first specifier is used for formatting the key and the second specifier is used for formatting the value. The order can be changed with positional arguments. For example "%(%2$s (%1$s), %)" will write the value, followed by the key in parenthesis. |

|<td rowspan="2">Enum</td> 's' | The name of the value. If the name is not available, the base value is used, preceeded by a cast. |

| All, but 's' | Enums can be formatted with all format characters that can be used with the base value. In that case they are formatted like the base value. |

|<td rowspan="3">Input Range</td> 's' | When the elements of the range are characters, they are written like a string. In all other cases, the elements are enclosed by square brackets and separated by a comma and a space. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="1">Struct</td> 's' | When the struct has neither an applicable toString nor is an input range, it is formatted as follows: StructType(field1, field2, ...). |

|<td rowspan="1">Class</td> 's' | When the class has neither an applicable toString nor is an input range, it is formatted as the fully qualified name of the class. |

|<td rowspan="1">Union</td> 's' | When the union has neither an applicable toString nor is an input range, it is formatted as its base name. |

|<td rowspan="2">Pointer</td> 's' | A null pointer is formatted as 'null'. All other pointers are formatted as hexadecimal numbers with the format character 'X'. |

| 'x', 'X' | Formatted as a hexadecimal number. |

|<td rowspan="3">SIMD vector</td> 's' | The array is surrounded by square brackets and the elements are separated by a comma and a space. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="1">Delegate</td> 's', 'r', compound | As the .stringof of this delegate treated as a string.

Please note: The implementation is currently buggy and its use is discouraged. |

Source

std/format/package.d

Examples

Simple use:

// Easiest way is to use `%s` everywhere:
assert(format("I got %s %s for %s euros.", 30, "eggs", 5.27) == "I got 30 eggs for 5.27 euros.");

// Other format characters provide more control:
assert(format("I got %b %(%X%) for %f euros.", 30, "eggs", 5.27) == "I got 11110 65676773 for 5.270000 euros.");

Compound specifiers allow formatting arrays and other compound types:

/*
The trailing end of the sub-format string following the specifier for
each item is interpreted as the array delimiter, and is therefore
omitted following the last array item:
 */
    assert(format("My items are %(%s %).", [1,2,3]) == "My items are 1 2 3.");
    assert(format("My items are %(%s, %).", [1,2,3]) == "My items are 1, 2, 3.");

/*
The "%|" delimiter specifier may be used to indicate where the
delimiter begins, so that the portion of the format string prior to
it will be retained in the last array element:
 */
    assert(format("My items are %(-%s-%|, %).", [1,2,3]) == "My items are -1-, -2-, -3-.");

/*
These compound format specifiers may be nested in the case of a
nested array argument:
 */
    auto mat = [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]];

    assert(format("%(%(%d %) - %)", mat), "1 2 3 - 4 5 6 - 7 8 9");
    assert(format("[%(%(%d %) - %)]", mat), "[1 2 3 - 4 5 6 - 7 8 9]");
    assert(format("[%([%(%d %)]%| - %)]", mat), "[1 2 3] - [4 5 6] - [7 8 9]");

/*
Strings and characters are escaped automatically inside compound
format specifiers. To avoid this behavior, use "%-(" instead of "%(":
 */
    assert(format("My friends are %s.", ["John", "Nancy"]) == `My friends are ["John", "Nancy"].`);
    assert(format("My friends are %(%s, %).", ["John", "Nancy"]) == `My friends are "John", "Nancy".`);
    assert(format("My friends are %-(%s, %).", ["John", "Nancy"]) == `My friends are John, Nancy.`);

Using parameters:

// Flags can be used to influence to outcome:
assert(format("%g != %+#g", 3.14, 3.14) == "3.14 != +3.14000");

// Width and precision help to arrange the formatted result:
assert(format(">%10.2f<", 1234.56789) == ">   1234.57<");

// Numbers can be grouped:
assert(format("%,4d", int.max) == "21,4748,3647");

// It's possible to specify the position of an argument:
assert(format("%3$s %1$s", 3, 17, 5) == "5 3");

Providing parameters as arguments:

// Width as argument
assert(format(">%*s<", 10, "abc") == ">       abc<");

// Precision as argument
assert(format(">%.*f<", 5, 123.2) == ">123.20000<");

// Grouping as argument
assert(format("%,*d", 1, int.max) == "2,1,4,7,4,8,3,6,4,7");

// Grouping separator as argument
assert(format("%,3?d", '_', int.max) == "2_147_483_647");

// All at once
assert(format("%*.*,*?d", 20, 15, 6, '/', int.max) == "   000/002147/483647");
@copyrightCopyright The D Language Foundation 2000-2021.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, and Kenji Hara
format
:
(alias template) format = std.format.format(Char, Args...)(in Char[] fmt, Args args) if (isSomeChar!Char)

Converts its arguments according to a format string into a string.

The second version of format takes the format string as template argument. In this case, it is checked for consistency at compile-time and produces slightly faster code, because the length of the output buffer can be estimated in advance.

Params: fmt = a $(MREF_ALTTEXT format string, std,format) args = a variadic list of arguments to be formatted Char = character type of fmt Args = a variadic list of types of the arguments

Returns: The formatted string.

Throws: A $(LREF FormatException) if formatting did not succeed.

See_Also: $(LREF sformat) for a variant, that tries to avoid garbage collection.

format
;
return
string std.format.format!("%+.6g dB", const(double))(const(double) __param_0) pure @safe

Examples

The format string can be checked at compile-time:

auto s = format!"%s is %s"("Pi", 3.14);
assert(s == "Pi is 3.14");

// This line doesn't compile, because 3.14 cannot be formatted with %d:
// s = format!"%s is %d"("Pi", 3.14);
format
!"%+.6g dB"(
(field) double uom_quantity_logarithmic.Decibels.db
db
);
} } /// A minimal `ℤ¹`-graded quantity (a single length exponent) — the /// free-abelian-group model in miniature, present only to make the contrast /// concrete. Its `+` is ORDINARY LINEAR addition within a grade. The /// dimensionless grade `Quantity!0` IS a linear `Ratio` — but its `+` is the /// WRONG operation for a stop: `Quantity!0(2) + Quantity!0(2) == 4`, whereas /// composing `+1 EV` twice is `+2 EV`, i.e. a linear `×4`. Same dimensionless /// numbers, different group — which is precisely why a log unit is not a grade. struct
(struct) uom_quantity_logarithmic.Quantity!0

A minimal ℤ¹-graded quantity (a single length exponent) — the free-abelian-group model in miniature, present only to make the contrast concrete. Its + is ORDINARY LINEAR addition within a grade. The dimensionless grade Quantity`!0` IS a linear `Ratio` — but its `+` is the WRONG operation for a stop: Quantity!0(2) + Quantity!0(2) == 4, whereas composing +1 EV twice is +2 EV, i.e. a linear ×4. Same dimensionless numbers, different group — which is precisely why a log unit is not a grade.

Quantity
(int lengthExp)
{ double
(field) double uom_quantity_logarithmic.Quantity!0.value
value
;
(struct) uom_quantity_logarithmic.Quantity!0

A minimal ℤ¹-graded quantity (a single length exponent) — the free-abelian-group model in miniature, present only to make the contrast concrete. Its + is ORDINARY LINEAR addition within a grade. The dimensionless grade Quantity`!0` IS a linear `Ratio` — but its `+` is the WRONG operation for a stop: Quantity!0(2) + Quantity!0(2) == 4, whereas composing +1 EV twice is +2 EV, i.e. a linear ×4. Same dimensionless numbers, different group — which is precisely why a log unit is not a grade.

Quantity
uom_quantity_logarithmic.Quantity!0 uom_quantity_logarithmic.Quantity!0.opBinary!"+"(in uom_quantity_logarithmic.Quantity!0 rhs) const pure nothrow @nogc @safe
opBinary
(string op)(in
(struct) uom_quantity_logarithmic.Quantity!0

A minimal ℤ¹-graded quantity (a single length exponent) — the free-abelian-group model in miniature, present only to make the contrast concrete. Its + is ORDINARY LINEAR addition within a grade. The dimensionless grade Quantity`!0` IS a linear `Ratio` — but its `+` is the WRONG operation for a stop: Quantity!0(2) + Quantity!0(2) == 4, whereas composing +1 EV twice is +2 EV, i.e. a linear ×4. Same dimensionless numbers, different group — which is precisely why a log unit is not a grade.

Quantity
(parameter) const(uom_quantity_logarithmic.Quantity!0) rhs
rhs
) const @safe pure nothrow @nogc
if (op == "+" || op == "-") =>
(struct) uom_quantity_logarithmic.Quantity!0
Quantity
(mixin("value " ~ op ~ " rhs.value"));
auto
pure nothrow @nogc @safe auto opBinary(string op, int e)(in Quantity!e rhs) const
opBinary
(string op, int e)(in Quantity!e
(parameter) Quantity!e rhs
rhs
) const @safe pure nothrow @nogc
if (op == "*" || op == "/") =>
(template instance) Quantity!(op == "*" ? lengthExp + e : lengthExp - e)
Quantity
!(op == "*" ? lengthExp + e : lengthExp - e)(
mixin("value " ~ op ~ " rhs.value")); } /// The dimensionless grade: a bare ratio with LINEAR `+`. alias
(alias) uom_quantity_logarithmic.Dimensionless = uom_quantity_logarithmic.Quantity!0

The dimensionless grade: a bare ratio with LINEAR +.

Dimensionless
=
(struct) uom_quantity_logarithmic.Quantity!0

A minimal ℤ¹-graded quantity (a single length exponent) — the free-abelian-group model in miniature, present only to make the contrast concrete. Its + is ORDINARY LINEAR addition within a grade. The dimensionless grade Quantity`!0` IS a linear `Ratio` — but its `+` is the WRONG operation for a stop: Quantity!0(2) + Quantity!0(2) == 4, whereas composing +1 EV twice is +2 EV, i.e. a linear ×4. Same dimensionless numbers, different group — which is precisely why a log unit is not a grade.

Quantity
!0;
/// Per-channel RGB radiance/gain helpers (plain `double[3]`, zero-dep). A stop /// vector maps to a linear RGB gain through `2^ev` component-wise; this is /// NONLINEAR, hence not a vector space over radiance. double[3]
double[3] uom_quantity_logarithmic.rgbToLinear(in double[3] evPerChannel) pure nothrow @nogc @safe

Per-channel RGB radiance/gain helpers (plain double[3], zero-dep). A stop vector maps to a linear RGB gain through 2^ev component-wise; this is NONLINEAR, hence not a vector space over radiance.

rgbToLinear
(in double[3]
(parameter) const(double[3]) evPerChannel
evPerChannel
) @safe pure nothrow @nogc
{ double[3]
(local variable) double[3] lin
lin
;
static foreach (i; 0 .. 3)
(local variable) double[3] lin
lin
[
(constant) int uom_quantity_logarithmic.rgbToLinear.i = 0
i
] = 2.0 ^^
(parameter) const(double[3]) evPerChannel
evPerChannel
[
(constant) int uom_quantity_logarithmic.rgbToLinear.i = 0
i
];
return
(local variable) double[3] lin
lin
;
} @("Quantity.logarithmic.homomorphism-and-graded-mismatch") @safe pure nothrow @nogc unittest { // The core theorem, forward: log-domain `+` ≙ linear-domain `×`. // fromLinear(a) + fromLinear(b) == fromLinear(a * b). auto
(local variable) uom_quantity_logarithmic.Ratio a
a
=
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
(2.0);
auto
(local variable) uom_quantity_logarithmic.Ratio b
b
=
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
(4.0);
auto
(local variable) uom_quantity_logarithmic.Stops sumOfLogs
sumOfLogs
=
(struct) uom_quantity_logarithmic.Stops

A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. One stop doubles exposure. The payload ev lives in the ADDITIVE group (ℝ, +): composing two exposure adjustments ADDS their stop counts, which MULTIPLIES the underlying linear Ratio. Stops is therefore not a new dimension grade — it is the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +), meaningful only relative to a reference exposure.

Stops
.
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.fromLinear(in uom_quantity_logarithmic.Ratio r) pure nothrow @nogc @safe

Bridge from a linear ratio: log₂(factor). Defined only for a positive ratio — logarithms exist only on the positive multiplicative group, which is why a log unit needs a reference to be meaningful.

fromLinear
(
(local variable) uom_quantity_logarithmic.Ratio a
a
) +
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.opBinary!"+"(in uom_quantity_logarithmic.Stops rhs) const pure nothrow @nogc @safe

Compose gains: + stacks exposure adjustments, - removes one. LOG-domain addition ≙ LINEAR-domain multiplication (proven below).

Stops
.
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.fromLinear(in uom_quantity_logarithmic.Ratio r) pure nothrow @nogc @safe

Bridge from a linear ratio: log₂(factor). Defined only for a positive ratio — logarithms exist only on the positive multiplicative group, which is why a log unit needs a reference to be meaningful.

fromLinear
(
(local variable) uom_quantity_logarithmic.Ratio b
b
);
auto
(local variable) uom_quantity_logarithmic.Stops logOfProduct
logOfProduct
=
(struct) uom_quantity_logarithmic.Stops

A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. One stop doubles exposure. The payload ev lives in the ADDITIVE group (ℝ, +): composing two exposure adjustments ADDS their stop counts, which MULTIPLIES the underlying linear Ratio. Stops is therefore not a new dimension grade — it is the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +), meaningful only relative to a reference exposure.

Stops
.
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.fromLinear(in uom_quantity_logarithmic.Ratio r) pure nothrow @nogc @safe

Bridge from a linear ratio: log₂(factor). Defined only for a positive ratio — logarithms exist only on the positive multiplicative group, which is why a log unit needs a reference to be meaningful.

fromLinear
(
(local variable) uom_quantity_logarithmic.Ratio a
a
*
uom_quantity_logarithmic.Ratio uom_quantity_logarithmic.Ratio.opBinary!"*"(in uom_quantity_logarithmic.Ratio rhs) const pure nothrow @nogc @safe

The multiplicative group op: gains compose by *, invert by /.

b
);
assert(
bool std.math.operations.isClose!(double, double, double)(double lhs, double rhs, double maxRelDiff = 1e-09, double maxAbsDiff = 0.0) pure nothrow @nogc @safe

Computes whether two values are approximately equal, admitting a maximum relative difference, and a maximum absolute difference.

Examples

assert(isClose(1.0,0.999_999_999));
assert(isClose(0.001, 0.000_999_999_999));
assert(isClose(1_000_000_000.0,999_999_999.0));

assert(isClose(17.123_456_789, 17.123_456_78));
assert(!isClose(17.123_456_789, 17.123_45));

// use explicit 3rd parameter for less (or more) accuracy
assert(isClose(17.123_456_789, 17.123_45, 1e-6));
assert(!isClose(17.123_456_789, 17.123_45, 1e-7));

// use 4th parameter when comparing close to zero
assert(!isClose(1e-100, 0.0));
assert(isClose(1e-100, 0.0, 0.0, 1e-90));
assert(!isClose(1e-10, -1e-10));
assert(isClose(1e-10, -1e-10, 0.0, 1e-9));
assert(!isClose(1e-300, 1e-298));
assert(isClose(1e-300, 1e-298, 0.0, 1e-200));

// different default limits for different floating point types
assert(isClose(1.0f, 0.999_99f));
assert(!isClose(1.0, 0.999_99));
static if (real.sizeof > double.sizeof)
    assert(!isClose(1.0L, 0.999_999_999L));
assert(isClose([1.0, 2.0, 3.0], [0.999_999_999, 2.000_000_001, 3.0]));
assert(!isClose([1.0, 2.0], [0.999_999_999, 2.000_000_001, 3.0]));
assert(!isClose([1.0, 2.0, 3.0], [0.999_999_999, 2.000_000_001]));

assert(isClose([2.0, 1.999_999_999, 2.000_000_001], 2.0));
assert(isClose(2.0, [2.0, 1.999_999_999, 2.000_000_001]));
@paramlhs First item to compare.@paramrhs Second item to compare.@parammaxRelDiff Maximum allowable relative difference. Setting to 0.0 disables this check. Default depends on the type of lhs and rhs: It is approximately half the number of decimal digits of precision of the smaller type.@parammaxAbsDiff Maximum absolute difference. This is mainly usefull for comparing values to zero. Setting to 0.0 disables this check. Defaults to 0.0.@returns

true if the two items are approximately equal under either criterium. It is sufficient, when value satisfies one of the two criteria.

If one item is a range, and the other is a single value, then the result is the logical and-ing of calling isClose on each element of the ranged item against the single item. If both items are ranges, then isClose returns true if and only if the ranges have the same number of elements and if isClose evaluates to true for each pair of elements.

@seeUse feqrel to get the number of equal bits in the mantissa.
isClose
(
(local variable) uom_quantity_logarithmic.Stops sumOfLogs
sumOfLogs
.
(field) double uom_quantity_logarithmic.Stops.ev
ev
,
(local variable) uom_quantity_logarithmic.Stops logOfProduct
logOfProduct
.
(field) double uom_quantity_logarithmic.Stops.ev
ev
));
assert(
bool std.math.operations.isClose!(double, double, double)(double lhs, double rhs, double maxRelDiff = 1e-09, double maxAbsDiff = 0.0) pure nothrow @nogc @safe

Computes whether two values are approximately equal, admitting a maximum relative difference, and a maximum absolute difference.

Examples

assert(isClose(1.0,0.999_999_999));
assert(isClose(0.001, 0.000_999_999_999));
assert(isClose(1_000_000_000.0,999_999_999.0));

assert(isClose(17.123_456_789, 17.123_456_78));
assert(!isClose(17.123_456_789, 17.123_45));

// use explicit 3rd parameter for less (or more) accuracy
assert(isClose(17.123_456_789, 17.123_45, 1e-6));
assert(!isClose(17.123_456_789, 17.123_45, 1e-7));

// use 4th parameter when comparing close to zero
assert(!isClose(1e-100, 0.0));
assert(isClose(1e-100, 0.0, 0.0, 1e-90));
assert(!isClose(1e-10, -1e-10));
assert(isClose(1e-10, -1e-10, 0.0, 1e-9));
assert(!isClose(1e-300, 1e-298));
assert(isClose(1e-300, 1e-298, 0.0, 1e-200));

// different default limits for different floating point types
assert(isClose(1.0f, 0.999_99f));
assert(!isClose(1.0, 0.999_99));
static if (real.sizeof > double.sizeof)
    assert(!isClose(1.0L, 0.999_999_999L));
assert(isClose([1.0, 2.0, 3.0], [0.999_999_999, 2.000_000_001, 3.0]));
assert(!isClose([1.0, 2.0], [0.999_999_999, 2.000_000_001, 3.0]));
assert(!isClose([1.0, 2.0, 3.0], [0.999_999_999, 2.000_000_001]));

assert(isClose([2.0, 1.999_999_999, 2.000_000_001], 2.0));
assert(isClose(2.0, [2.0, 1.999_999_999, 2.000_000_001]));
@paramlhs First item to compare.@paramrhs Second item to compare.@parammaxRelDiff Maximum allowable relative difference. Setting to 0.0 disables this check. Default depends on the type of lhs and rhs: It is approximately half the number of decimal digits of precision of the smaller type.@parammaxAbsDiff Maximum absolute difference. This is mainly usefull for comparing values to zero. Setting to 0.0 disables this check. Defaults to 0.0.@returns

true if the two items are approximately equal under either criterium. It is sufficient, when value satisfies one of the two criteria.

If one item is a range, and the other is a single value, then the result is the logical and-ing of calling isClose on each element of the ranged item against the single item. If both items are ranges, then isClose returns true if and only if the ranges have the same number of elements and if isClose evaluates to true for each pair of elements.

@seeUse feqrel to get the number of equal bits in the mantissa.
isClose
(
(local variable) uom_quantity_logarithmic.Stops sumOfLogs
sumOfLogs
.
(field) double uom_quantity_logarithmic.Stops.ev
ev
, 3.0)); // 1 EV + 2 EV = 3 EV
// The core theorem, inverse: (s + t).toLinear ≈ s.toLinear * t.toLinear. auto
(local variable) uom_quantity_logarithmic.Stops s
s
=
(struct) uom_quantity_logarithmic.Stops

A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. One stop doubles exposure. The payload ev lives in the ADDITIVE group (ℝ, +): composing two exposure adjustments ADDS their stop counts, which MULTIPLIES the underlying linear Ratio. Stops is therefore not a new dimension grade — it is the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +), meaningful only relative to a reference exposure.

Stops
(1.0);
auto
(local variable) uom_quantity_logarithmic.Stops t
t
=
(struct) uom_quantity_logarithmic.Stops

A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. One stop doubles exposure. The payload ev lives in the ADDITIVE group (ℝ, +): composing two exposure adjustments ADDS their stop counts, which MULTIPLIES the underlying linear Ratio. Stops is therefore not a new dimension grade — it is the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +), meaningful only relative to a reference exposure.

Stops
(2.0);
assert(
bool std.math.operations.isClose!(double, double, double)(double lhs, double rhs, double maxRelDiff = 1e-09, double maxAbsDiff = 0.0) pure nothrow @nogc @safe

Computes whether two values are approximately equal, admitting a maximum relative difference, and a maximum absolute difference.

Examples

assert(isClose(1.0,0.999_999_999));
assert(isClose(0.001, 0.000_999_999_999));
assert(isClose(1_000_000_000.0,999_999_999.0));

assert(isClose(17.123_456_789, 17.123_456_78));
assert(!isClose(17.123_456_789, 17.123_45));

// use explicit 3rd parameter for less (or more) accuracy
assert(isClose(17.123_456_789, 17.123_45, 1e-6));
assert(!isClose(17.123_456_789, 17.123_45, 1e-7));

// use 4th parameter when comparing close to zero
assert(!isClose(1e-100, 0.0));
assert(isClose(1e-100, 0.0, 0.0, 1e-90));
assert(!isClose(1e-10, -1e-10));
assert(isClose(1e-10, -1e-10, 0.0, 1e-9));
assert(!isClose(1e-300, 1e-298));
assert(isClose(1e-300, 1e-298, 0.0, 1e-200));

// different default limits for different floating point types
assert(isClose(1.0f, 0.999_99f));
assert(!isClose(1.0, 0.999_99));
static if (real.sizeof > double.sizeof)
    assert(!isClose(1.0L, 0.999_999_999L));
assert(isClose([1.0, 2.0, 3.0], [0.999_999_999, 2.000_000_001, 3.0]));
assert(!isClose([1.0, 2.0], [0.999_999_999, 2.000_000_001, 3.0]));
assert(!isClose([1.0, 2.0, 3.0], [0.999_999_999, 2.000_000_001]));

assert(isClose([2.0, 1.999_999_999, 2.000_000_001], 2.0));
assert(isClose(2.0, [2.0, 1.999_999_999, 2.000_000_001]));
@paramlhs First item to compare.@paramrhs Second item to compare.@parammaxRelDiff Maximum allowable relative difference. Setting to 0.0 disables this check. Default depends on the type of lhs and rhs: It is approximately half the number of decimal digits of precision of the smaller type.@parammaxAbsDiff Maximum absolute difference. This is mainly usefull for comparing values to zero. Setting to 0.0 disables this check. Defaults to 0.0.@returns

true if the two items are approximately equal under either criterium. It is sufficient, when value satisfies one of the two criteria.

If one item is a range, and the other is a single value, then the result is the logical and-ing of calling isClose on each element of the ranged item against the single item. If both items are ranges, then isClose returns true if and only if the ranges have the same number of elements and if isClose evaluates to true for each pair of elements.

@seeUse feqrel to get the number of equal bits in the mantissa.
isClose
((
(local variable) uom_quantity_logarithmic.Stops s
s
+
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.opBinary!"+"(in uom_quantity_logarithmic.Stops rhs) const pure nothrow @nogc @safe

Compose gains: + stacks exposure adjustments, - removes one. LOG-domain addition ≙ LINEAR-domain multiplication (proven below).

t
).
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.opBinary!"+"(in uom_quantity_logarithmic.Stops rhs) const pure nothrow @nogc @safe

Compose gains: + stacks exposure adjustments, - removes one. LOG-domain addition ≙ LINEAR-domain multiplication (proven below).

toLinear
.
(field) double uom_quantity_logarithmic.Ratio.factor
factor
,
(local variable) uom_quantity_logarithmic.Stops s
s
.
uom_quantity_logarithmic.Ratio uom_quantity_logarithmic.Stops.toLinear() const pure nothrow @nogc @safe

Bridge to the linear domain: 2^ev. This is the isomorphism's inverse and is NONLINEAR in ev — the root of the vector nonlinearity below.

toLinear
.
(field) double uom_quantity_logarithmic.Ratio.factor
factor
*
(local variable) uom_quantity_logarithmic.Stops t
t
.
uom_quantity_logarithmic.Ratio uom_quantity_logarithmic.Stops.toLinear() const pure nothrow @nogc @safe

Bridge to the linear domain: 2^ev. This is the isomorphism's inverse and is NONLINEAR in ev — the root of the vector nonlinearity below.

toLinear
.
(field) double uom_quantity_logarithmic.Ratio.factor
factor
));
assert(
bool std.math.operations.isClose!(double, double, double)(double lhs, double rhs, double maxRelDiff = 1e-09, double maxAbsDiff = 0.0) pure nothrow @nogc @safe

Computes whether two values are approximately equal, admitting a maximum relative difference, and a maximum absolute difference.

Examples

assert(isClose(1.0,0.999_999_999));
assert(isClose(0.001, 0.000_999_999_999));
assert(isClose(1_000_000_000.0,999_999_999.0));

assert(isClose(17.123_456_789, 17.123_456_78));
assert(!isClose(17.123_456_789, 17.123_45));

// use explicit 3rd parameter for less (or more) accuracy
assert(isClose(17.123_456_789, 17.123_45, 1e-6));
assert(!isClose(17.123_456_789, 17.123_45, 1e-7));

// use 4th parameter when comparing close to zero
assert(!isClose(1e-100, 0.0));
assert(isClose(1e-100, 0.0, 0.0, 1e-90));
assert(!isClose(1e-10, -1e-10));
assert(isClose(1e-10, -1e-10, 0.0, 1e-9));
assert(!isClose(1e-300, 1e-298));
assert(isClose(1e-300, 1e-298, 0.0, 1e-200));

// different default limits for different floating point types
assert(isClose(1.0f, 0.999_99f));
assert(!isClose(1.0, 0.999_99));
static if (real.sizeof > double.sizeof)
    assert(!isClose(1.0L, 0.999_999_999L));
assert(isClose([1.0, 2.0, 3.0], [0.999_999_999, 2.000_000_001, 3.0]));
assert(!isClose([1.0, 2.0], [0.999_999_999, 2.000_000_001, 3.0]));
assert(!isClose([1.0, 2.0, 3.0], [0.999_999_999, 2.000_000_001]));

assert(isClose([2.0, 1.999_999_999, 2.000_000_001], 2.0));
assert(isClose(2.0, [2.0, 1.999_999_999, 2.000_000_001]));
@paramlhs First item to compare.@paramrhs Second item to compare.@parammaxRelDiff Maximum allowable relative difference. Setting to 0.0 disables this check. Default depends on the type of lhs and rhs: It is approximately half the number of decimal digits of precision of the smaller type.@parammaxAbsDiff Maximum absolute difference. This is mainly usefull for comparing values to zero. Setting to 0.0 disables this check. Defaults to 0.0.@returns

true if the two items are approximately equal under either criterium. It is sufficient, when value satisfies one of the two criteria.

If one item is a range, and the other is a single value, then the result is the logical and-ing of calling isClose on each element of the ranged item against the single item. If both items are ranges, then isClose returns true if and only if the ranges have the same number of elements and if isClose evaluates to true for each pair of elements.

@seeUse feqrel to get the number of equal bits in the mantissa.
isClose
((
(local variable) uom_quantity_logarithmic.Stops s
s
+
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.opBinary!"+"(in uom_quantity_logarithmic.Stops rhs) const pure nothrow @nogc @safe

Compose gains: + stacks exposure adjustments, - removes one. LOG-domain addition ≙ LINEAR-domain multiplication (proven below).

t
).
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.opBinary!"+"(in uom_quantity_logarithmic.Stops rhs) const pure nothrow @nogc @safe

Compose gains: + stacks exposure adjustments, - removes one. LOG-domain addition ≙ LINEAR-domain multiplication (proven below).

toLinear
.
(field) double uom_quantity_logarithmic.Ratio.factor
factor
, 8.0)); // +3 EV == ×8
// A log unit is NOT the dimensionless grade: the graded `+` is linear. static assert(is(typeof(
(struct) uom_quantity_logarithmic.Quantity!0
Dimensionless
(2) +
uom_quantity_logarithmic.Quantity!0 uom_quantity_logarithmic.Quantity!0.opBinary!"+"(in uom_quantity_logarithmic.Quantity!0 rhs) const pure nothrow @nogc @safe
Dimensionless
(2)) == Dimensionless));
assert(
(struct) uom_quantity_logarithmic.Quantity!0
Dimensionless
(2).
(field) double uom_quantity_logarithmic.Quantity!0.value
value
+
(struct) uom_quantity_logarithmic.Quantity!0
Dimensionless
(2).
(field) double uom_quantity_logarithmic.Quantity!0.value
value
== 4.0); // linear add
// ...while composing the SAME ratio-of-2 twice as stops gives ×4, not 4. assert(
bool std.math.operations.isClose!(double, double, double)(double lhs, double rhs, double maxRelDiff = 1e-09, double maxAbsDiff = 0.0) pure nothrow @nogc @safe

Computes whether two values are approximately equal, admitting a maximum relative difference, and a maximum absolute difference.

Examples

assert(isClose(1.0,0.999_999_999));
assert(isClose(0.001, 0.000_999_999_999));
assert(isClose(1_000_000_000.0,999_999_999.0));

assert(isClose(17.123_456_789, 17.123_456_78));
assert(!isClose(17.123_456_789, 17.123_45));

// use explicit 3rd parameter for less (or more) accuracy
assert(isClose(17.123_456_789, 17.123_45, 1e-6));
assert(!isClose(17.123_456_789, 17.123_45, 1e-7));

// use 4th parameter when comparing close to zero
assert(!isClose(1e-100, 0.0));
assert(isClose(1e-100, 0.0, 0.0, 1e-90));
assert(!isClose(1e-10, -1e-10));
assert(isClose(1e-10, -1e-10, 0.0, 1e-9));
assert(!isClose(1e-300, 1e-298));
assert(isClose(1e-300, 1e-298, 0.0, 1e-200));

// different default limits for different floating point types
assert(isClose(1.0f, 0.999_99f));
assert(!isClose(1.0, 0.999_99));
static if (real.sizeof > double.sizeof)
    assert(!isClose(1.0L, 0.999_999_999L));
assert(isClose([1.0, 2.0, 3.0], [0.999_999_999, 2.000_000_001, 3.0]));
assert(!isClose([1.0, 2.0], [0.999_999_999, 2.000_000_001, 3.0]));
assert(!isClose([1.0, 2.0, 3.0], [0.999_999_999, 2.000_000_001]));

assert(isClose([2.0, 1.999_999_999, 2.000_000_001], 2.0));
assert(isClose(2.0, [2.0, 1.999_999_999, 2.000_000_001]));
@paramlhs First item to compare.@paramrhs Second item to compare.@parammaxRelDiff Maximum allowable relative difference. Setting to 0.0 disables this check. Default depends on the type of lhs and rhs: It is approximately half the number of decimal digits of precision of the smaller type.@parammaxAbsDiff Maximum absolute difference. This is mainly usefull for comparing values to zero. Setting to 0.0 disables this check. Defaults to 0.0.@returns

true if the two items are approximately equal under either criterium. It is sufficient, when value satisfies one of the two criteria.

If one item is a range, and the other is a single value, then the result is the logical and-ing of calling isClose on each element of the ranged item against the single item. If both items are ranges, then isClose returns true if and only if the ranges have the same number of elements and if isClose evaluates to true for each pair of elements.

@seeUse feqrel to get the number of equal bits in the mantissa.
isClose
((
(struct) uom_quantity_logarithmic.Stops

A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. One stop doubles exposure. The payload ev lives in the ADDITIVE group (ℝ, +): composing two exposure adjustments ADDS their stop counts, which MULTIPLIES the underlying linear Ratio. Stops is therefore not a new dimension grade — it is the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +), meaningful only relative to a reference exposure.

Stops
.
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.fromLinear(in uom_quantity_logarithmic.Ratio r) pure nothrow @nogc @safe

Bridge from a linear ratio: log₂(factor). Defined only for a positive ratio — logarithms exist only on the positive multiplicative group, which is why a log unit needs a reference to be meaningful.

fromLinear
(
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
(2.0)) +
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.opBinary!"+"(in uom_quantity_logarithmic.Stops rhs) const pure nothrow @nogc @safe

Compose gains: + stacks exposure adjustments, - removes one. LOG-domain addition ≙ LINEAR-domain multiplication (proven below).

Stops
.
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.fromLinear(in uom_quantity_logarithmic.Ratio r) pure nothrow @nogc @safe

Bridge from a linear ratio: log₂(factor). Defined only for a positive ratio — logarithms exist only on the positive multiplicative group, which is why a log unit needs a reference to be meaningful.

fromLinear
(
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
(2.0)))
.
uom_quantity_logarithmic.Ratio uom_quantity_logarithmic.Stops.toLinear() const pure nothrow @nogc @safe

Bridge to the linear domain: 2^ev. This is the isomorphism's inverse and is NONLINEAR in ev — the root of the vector nonlinearity below.

toLinear
.
(field) double uom_quantity_logarithmic.Ratio.factor
factor
, 4.0));
} void
void D main() @safe
main
() @safe
{ import
(package) std
std
.
(module) std.stdio
Category Symbols
File handles _popen File isFileHandle openNetwork stderr stdin stdout
Reading chunks lines readf readfln readln
Writing toFile write writef writefln writeln
Misc KeepTerminator LockType StdioException

Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio is publically imported when importing std.stdio.

There are three layers of I/O:

  1. The lowest layer is the operating system layer. The two main schemes are Windows and Posix.

  2. C's stdio.h which unifies the two operating system schemes.

  3. std.stdio, this module, unifies the various stdio.h implementations into a high level package for D programs.

Source

std/stdio.d

@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Alex Rønne Petersen
stdio
:
(alias template) writeln = std.stdio.writeln(T...)(T args)

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Params: args = the items to write to stdout

Throws: In case of an I/O error, throws an $(LREF StdioException). Example: Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main() { string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }

} ---

writeln
;
// A raytracer holds linear radiance; the photographer thinks in stops. auto
(local variable) uom_quantity_logarithmic.Ratio baseGain
baseGain
=
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
(1.0); // reference exposure (×1)
auto
(local variable) uom_quantity_logarithmic.Stops pushOne
pushOne
=
(struct) uom_quantity_logarithmic.Stops

A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. One stop doubles exposure. The payload ev lives in the ADDITIVE group (ℝ, +): composing two exposure adjustments ADDS their stop counts, which MULTIPLIES the underlying linear Ratio. Stops is therefore not a new dimension grade — it is the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +), meaningful only relative to a reference exposure.

Stops
(1.0); // +1 stop
auto
(local variable) uom_quantity_logarithmic.Stops pushTwo
pushTwo
=
(struct) uom_quantity_logarithmic.Stops

A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. One stop doubles exposure. The payload ev lives in the ADDITIVE group (ℝ, +): composing two exposure adjustments ADDS their stop counts, which MULTIPLIES the underlying linear Ratio. Stops is therefore not a new dimension grade — it is the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +), meaningful only relative to a reference exposure.

Stops
(2.0); // +2 stops
// Compose exposure adjustments by ADDING stops... auto
(local variable) uom_quantity_logarithmic.Stops total
total
=
(local variable) uom_quantity_logarithmic.Stops pushOne
pushOne
+
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.opBinary!"+"(in uom_quantity_logarithmic.Stops rhs) const pure nothrow @nogc @safe

Compose gains: + stacks exposure adjustments, - removes one. LOG-domain addition ≙ LINEAR-domain multiplication (proven below).

pushTwo
; // +3 EV
// ...which MULTIPLIES the underlying linear ratio (×2 · ×4 = ×8). auto
(local variable) uom_quantity_logarithmic.Ratio linear
linear
=
(local variable) uom_quantity_logarithmic.Stops total
total
.
uom_quantity_logarithmic.Ratio uom_quantity_logarithmic.Stops.toLinear() const pure nothrow @nogc @safe

Bridge to the linear domain: 2^ev. This is the isomorphism's inverse and is NONLINEAR in ev — the root of the vector nonlinearity below.

toLinear
;
void std.stdio.writeln!(string, uom_quantity_logarithmic.Stops, string, uom_quantity_logarithmic.Ratio, string)(string __param_0, uom_quantity_logarithmic.Stops __param_1, string __param_2, uom_quantity_logarithmic.Ratio __param_3, string __param_4) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("+1 EV = ",
(local variable) uom_quantity_logarithmic.Stops pushOne
pushOne
, " (",
(local variable) uom_quantity_logarithmic.Stops pushOne
pushOne
.
uom_quantity_logarithmic.Ratio uom_quantity_logarithmic.Stops.toLinear() const pure nothrow @nogc @safe

Bridge to the linear domain: 2^ev. This is the isomorphism's inverse and is NONLINEAR in ev — the root of the vector nonlinearity below.

toLinear
, ")");
void std.stdio.writeln!(string, uom_quantity_logarithmic.Stops, string, uom_quantity_logarithmic.Ratio, string)(string __param_0, uom_quantity_logarithmic.Stops __param_1, string __param_2, uom_quantity_logarithmic.Ratio __param_3, string __param_4) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("+2 EV = ",
(local variable) uom_quantity_logarithmic.Stops pushTwo
pushTwo
, " (",
(local variable) uom_quantity_logarithmic.Stops pushTwo
pushTwo
.
uom_quantity_logarithmic.Ratio uom_quantity_logarithmic.Stops.toLinear() const pure nothrow @nogc @safe

Bridge to the linear domain: 2^ev. This is the isomorphism's inverse and is NONLINEAR in ev — the root of the vector nonlinearity below.

toLinear
, ")");
void std.stdio.writeln!(string, uom_quantity_logarithmic.Stops, string, uom_quantity_logarithmic.Ratio, string)(string __param_0, uom_quantity_logarithmic.Stops __param_1, string __param_2, uom_quantity_logarithmic.Ratio __param_3, string __param_4) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("(+1 EV) + (+2 EV) = ",
(local variable) uom_quantity_logarithmic.Stops total
total
, " (",
(local variable) uom_quantity_logarithmic.Ratio linear
linear
, ")");
// Round trip through the bridge, both directions. auto
(local variable) uom_quantity_logarithmic.Ratio a
a
=
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
(2.0),
(local variable) uom_quantity_logarithmic.Ratio b
b
=
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
(4.0);
void std.stdio.writeln!(string, uom_quantity_logarithmic.Stops, string, uom_quantity_logarithmic.Stops)(string __param_0, uom_quantity_logarithmic.Stops __param_1, string __param_2, uom_quantity_logarithmic.Stops __param_3) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("fromLinear(×2)+fromLinear(×4) = ",
(struct) uom_quantity_logarithmic.Stops

A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. One stop doubles exposure. The payload ev lives in the ADDITIVE group (ℝ, +): composing two exposure adjustments ADDS their stop counts, which MULTIPLIES the underlying linear Ratio. Stops is therefore not a new dimension grade — it is the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +), meaningful only relative to a reference exposure.

Stops
.
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.fromLinear(in uom_quantity_logarithmic.Ratio r) pure nothrow @nogc @safe

Bridge from a linear ratio: log₂(factor). Defined only for a positive ratio — logarithms exist only on the positive multiplicative group, which is why a log unit needs a reference to be meaningful.

fromLinear
(
(local variable) uom_quantity_logarithmic.Ratio a
a
) +
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.opBinary!"+"(in uom_quantity_logarithmic.Stops rhs) const pure nothrow @nogc @safe

Compose gains: + stacks exposure adjustments, - removes one. LOG-domain addition ≙ LINEAR-domain multiplication (proven below).

Stops
.
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.fromLinear(in uom_quantity_logarithmic.Ratio r) pure nothrow @nogc @safe

Bridge from a linear ratio: log₂(factor). Defined only for a positive ratio — logarithms exist only on the positive multiplicative group, which is why a log unit needs a reference to be meaningful.

fromLinear
(
(local variable) uom_quantity_logarithmic.Ratio b
b
),
" == fromLinear(×2·×4) = ",
(struct) uom_quantity_logarithmic.Stops

A LOGARITHMIC quantity: a photographic stop / exposure value (EV), base-2. One stop doubles exposure. The payload ev lives in the ADDITIVE group (ℝ, +): composing two exposure adjustments ADDS their stop counts, which MULTIPLIES the underlying linear Ratio. Stops is therefore not a new dimension grade — it is the isomorphism log₂ : (ℝ_{>0}, ×) → (ℝ, +), meaningful only relative to a reference exposure.

Stops
.
uom_quantity_logarithmic.Stops uom_quantity_logarithmic.Stops.fromLinear(in uom_quantity_logarithmic.Ratio r) pure nothrow @nogc @safe

Bridge from a linear ratio: log₂(factor). Defined only for a positive ratio — logarithms exist only on the positive multiplicative group, which is why a log unit needs a reference to be meaningful.

fromLinear
(
(local variable) uom_quantity_logarithmic.Ratio a
a
*
uom_quantity_logarithmic.Ratio uom_quantity_logarithmic.Ratio.opBinary!"*"(in uom_quantity_logarithmic.Ratio rhs) const pure nothrow @nogc @safe

The multiplicative group op: gains compose by *, invert by /.

b
));
// A different log unit, different base/reference, same algebra: // +3 dB ≈ ×2 power; stacking it doubles again → ×4. auto
(local variable) uom_quantity_logarithmic.Decibels threeDb
threeDb
=
(struct) uom_quantity_logarithmic.Decibels

A second logarithmic quantity, on a different base and reference: power decibels, dB = 10·log₁₀(P/P_ref), so +3 dB ≈ ×2 power. It shares Stops' structure (add-in-log ≙ multiply-in-linear) but with base 10 and factor 10. That two log units with different constants share one algebra underscores the point: the log unit carries no dimension of its own — it is the reference and base that give it meaning, not a grade in the dimension group.

Decibels
.
uom_quantity_logarithmic.Decibels uom_quantity_logarithmic.Decibels.fromLinear(in uom_quantity_logarithmic.Ratio r) pure nothrow @nogc @safe
fromLinear
(
(struct) uom_quantity_logarithmic.Ratio

A plain dimensionless LINEAR ratio — an element of the multiplicative group (ℝ_{>0}, ×). This is what a raytracer actually accumulates and scales: a gain applied to linear radiance. Its group operation is MULTIPLICATION, its identity ``Ratio(1.0). It carries no dimension exponent (see the graded Quantity below: it is the Quantity!0 grade).

Ratio
(2.0));
void std.stdio.writeln!(string, uom_quantity_logarithmic.Decibels, string, uom_quantity_logarithmic.Decibels, string, uom_quantity_logarithmic.Ratio)(string __param_0, uom_quantity_logarithmic.Decibels __param_1, string __param_2, uom_quantity_logarithmic.Decibels __param_3, string __param_4, uom_quantity_logarithmic.Ratio __param_5) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("Decibels.fromLinear(×2) = ",
(local variable) uom_quantity_logarithmic.Decibels threeDb
threeDb
,
" (doubled) = ",
(local variable) uom_quantity_logarithmic.Decibels threeDb
threeDb
+
uom_quantity_logarithmic.Decibels uom_quantity_logarithmic.Decibels.opBinary!"+"(in uom_quantity_logarithmic.Decibels rhs) const pure nothrow @nogc @safe
threeDb
, " ≈ ", (
(local variable) uom_quantity_logarithmic.Decibels threeDb
threeDb
+
uom_quantity_logarithmic.Decibels uom_quantity_logarithmic.Decibels.opBinary!"+"(in uom_quantity_logarithmic.Decibels rhs) const pure nothrow @nogc @safe
threeDb
).
uom_quantity_logarithmic.Ratio uom_quantity_logarithmic.Decibels.toLinear() const pure nothrow @nogc @safe
toLinear
);
// Rejections are proofs. A log quantity is not a linear ratio, not a // dimensionless grade, and stops do not multiply — none of these compile. static assert(!__traits(compiles,
(local variable) uom_quantity_logarithmic.Stops pushOne
pushOne
+
(local variable) uom_quantity_logarithmic.Ratio baseGain
baseGain
),
"a logarithmic Stops is not a linear Ratio — they must not add"); static assert(!__traits(compiles,
(local variable) uom_quantity_logarithmic.Stops pushOne
pushOne
+
(struct) uom_quantity_logarithmic.Quantity!0
Dimensionless
(1)),
"a stop is not the dimensionless grade — its + is × on the ratio"); static assert(!__traits(compiles,
(local variable) uom_quantity_logarithmic.Stops pushOne
pushOne
*
(local variable) uom_quantity_logarithmic.Stops pushTwo
pushTwo
),
"multiplying two logarithms is not a group op on exposures"); static assert(__traits(compiles,
(local variable) uom_quantity_logarithmic.Stops pushOne
pushOne
+
(local variable) uom_quantity_logarithmic.Stops pushTwo
pushTwo
)); // ...but composing gains is.
// VECTOR NONLINEARITY. Two per-channel exposure adjustments, in stops. // You might hope to "add exposures" the way you add displacements — but // component-ADDING the stop vectors component-MULTIPLIES the linear RGB // gains, and does NOT correspond to adding the linear radiances. double[3]
(local variable) double[3] expA
expA
= [0.0, 1.0, 2.0]; // stops per channel
double[3]
(local variable) double[3] expB
expB
= [1.0, 1.0, 1.0];
double[3]
(local variable) double[3] summedStops
summedStops
= [
(local variable) double[3] expA
expA
[0] +
(local variable) double[3] expB
expB
[0],
(local variable) double[3] expA
expA
[1] +
(local variable) double[3] expB
expB
[1],
(local variable) double[3] expA
expA
[2] +
(local variable) double[3] expB
expB
[2]];
auto
(local variable) double[3] linA
linA
=
double[3] uom_quantity_logarithmic.rgbToLinear(in double[3] evPerChannel) pure nothrow @nogc @safe

Per-channel RGB radiance/gain helpers (plain double[3], zero-dep). A stop vector maps to a linear RGB gain through 2^ev component-wise; this is NONLINEAR, hence not a vector space over radiance.

rgbToLinear
(
(local variable) double[3] expA
expA
); // [×1, ×2, ×4]
auto
(local variable) double[3] linB
linB
=
double[3] uom_quantity_logarithmic.rgbToLinear(in double[3] evPerChannel) pure nothrow @nogc @safe

Per-channel RGB radiance/gain helpers (plain double[3], zero-dep). A stop vector maps to a linear RGB gain through 2^ev component-wise; this is NONLINEAR, hence not a vector space over radiance.

rgbToLinear
(
(local variable) double[3] expB
expB
); // [×2, ×2, ×2]
auto
(local variable) double[3] linOfSum
linOfSum
=
double[3] uom_quantity_logarithmic.rgbToLinear(in double[3] evPerChannel) pure nothrow @nogc @safe

Per-channel RGB radiance/gain helpers (plain double[3], zero-dep). A stop vector maps to a linear RGB gain through 2^ev component-wise; this is NONLINEAR, hence not a vector space over radiance.

rgbToLinear
(
(local variable) double[3] summedStops
summedStops
);
double[3]
(local variable) double[3] productOfLin
productOfLin
= [
(local variable) double[3] linA
linA
[0] *
(local variable) double[3] linB
linB
[0],
(local variable) double[3] linA
linA
[1] *
(local variable) double[3] linB
linB
[1],
(local variable) double[3] linA
linA
[2] *
(local variable) double[3] linB
linB
[2]];
double[3]
(local variable) double[3] sumOfLin
sumOfLin
= [
(local variable) double[3] linA
linA
[0] +
(local variable) double[3] linB
linB
[0],
(local variable) double[3] linA
linA
[1] +
(local variable) double[3] linB
linB
[1],
(local variable) double[3] linA
linA
[2] +
(local variable) double[3] linB
linB
[2]];
void std.stdio.writeln!(string, double[3], string, double[3])(string __param_0, double[3] __param_1, string __param_2, double[3] __param_3) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("stops A = ",
(local variable) double[3] expA
expA
, " → linear ",
(local variable) double[3] linA
linA
);
void std.stdio.writeln!(string, double[3], string, double[3])(string __param_0, double[3] __param_1, string __param_2, double[3] __param_3) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("stops B = ",
(local variable) double[3] expB
expB
, " → linear ",
(local variable) double[3] linB
linB
);
void std.stdio.writeln!(string, double[3], string, double[3], string, double[3], string)(string __param_0, double[3] __param_1, string __param_2, double[3] __param_3, string __param_4, double[3] __param_5, string __param_6) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("component-add stops = ",
(local variable) double[3] summedStops
summedStops
,
" → linear ",
(local variable) double[3] linOfSum
linOfSum
, " (== component-MULTIPLY ",
(local variable) double[3] productOfLin
productOfLin
, ")");
void std.stdio.writeln!(string, double[3], string, double[3], string)(string __param_0, double[3] __param_1, string __param_2, double[3] __param_3, string __param_4) @safe

Equivalent to write(args, '\n'). Calling writeln without arguments is valid and just prints a newline to the standard output.

Example

Reads stdin and writes it to stdout with an argument counter.

import std.stdio;

void main()
{
    string line;

    for (size_t count = 0; (line = readln) !is null; count++)
    {
         writeln("Input ", count, ": ", line);
    }
}
@paramargs the items to write to stdout@throwsIn case of an I/O error, throws an StdioException.
writeln
("linear radiance ADD would = ",
(local variable) double[3] sumOfLin
sumOfLin
,
" ≠ ",
(local variable) double[3] linOfSum
linOfSum
, " ⇒ a vector of log-values is nonlinear");
}