Перейти к содержимому
Топаз6.0 · До релиза
Загрузка →

Поиск в документации

Спецификация 6.0

Выберите результат стрелками и нажмите Enter, чтобы открыть его.

Введите имя API, номер диагностики, правило или тему проекта.

    Библиотека · std.decimal

    Decimal.div

    Divide at the requested decimal grid and return a recoverable zero divisor error.

    div(other: Decimal, scale: int, mode: RoundingMode = RoundingMode.HalfEven()) -> Result<Decimal, string>
    Модуль
    std.decimal →
    Получатель
    Decimal
    Минимальное число аргументов
    2
    Максимальное число аргументов
    3

    Declaration and parameters

    Ссылка

    Доступность

    Включено по умолчанию · Не определено

    Import std.decimal in language mode 5.21.

    The current compiler selects std/decimal.tpz for this language mode. Availability in other released editions and inclusion in each installed distribution are Pending.

    Получатель

    Decimal

    Ограничения параметров

    Decimal.div evaluates the exact quotient of its receiver and the divisor. For a nonzero divisor it rounds that quotient once to the requested decimal grid and returns Ok containing the normalized Decimal.

    The requested scale and mode have the same meaning as in Decimal.round. Omitting the mode selects RoundingMode.HalfEven(). Input scales and coefficient sizes do not introduce another precision limit or an intermediate rounding step.

    A nonterminating decimal quotient is rounded to the requested grid. A terminating quotient that is already on the grid remains exact. The canonical result scale can be smaller than the requested scale.

    Division signs follow ordinary numeric division. All six rounding modes apply to the signed exact quotient, including negative ties and results that round to zero.

    A zero divisor returns Err with the string Decimal.div: division by zero. This includes zero divided by zero and a divisor parsed from a negative zero spelling. This failure is a Result value and does not raise TPZ4002.

    A zero dividend and a nonzero divisor return Ok containing zero for every valid requested scale. An internal sum of operand and requested scales must not turn a nonzero divisor into a division by zero error.

    An invalid requested scale raises TPZ5001 during execution before the zero divisor is classified. The operation never replaces an invalid scale with zero or reports that scale error as a successful Result.

    The receiver, divisor, scale and explicitly supplied mode expressions evaluate once in that order before their values are validated. The operation preserves both operands.

    Результат

    The declared result type is Result<Decimal, string>.

    Эффекты

    Ошибки

    Result and effects

    Ссылка

    Round the exact quotient once with the supplied mode and normalize the result. The default mode is HalfEven. Invalid scales raise TPZ5001 during execution before zero divisor classification.

    An explicit result grid gives a nonterminating quotient a defined finite result while Result keeps a zero divisor recoverable.

    Resolved contracts

    Ссылка

    Related entries

    Ссылка

    std.decimal →

    Divide with an explicit result scale

    Ссылка
    Правилоtopaz.stdlib.contract.decimal-division.rule

    Divide with an explicit result scale

    Decimal.div evaluates the exact quotient of its receiver and the divisor. For a nonzero divisor it rounds that quotient once to the requested decimal grid and returns Ok containing the normalized Decimal.

    The requested scale and mode have the same meaning as in Decimal.round. Omitting the mode selects RoundingMode.HalfEven(). Input scales and coefficient sizes do not introduce another precision limit or an intermediate rounding step.

    A nonterminating decimal quotient is rounded to the requested grid. A terminating quotient that is already on the grid remains exact. The canonical result scale can be smaller than the requested scale.

    Division signs follow ordinary numeric division. All six rounding modes apply to the signed exact quotient, including negative ties and results that round to zero.

    A zero divisor returns Err with the string Decimal.div: division by zero. This includes zero divided by zero and a divisor parsed from a negative zero spelling. This failure is a Result value and does not raise TPZ4002.

    A zero dividend and a nonzero divisor return Ok containing zero for every valid requested scale. An internal sum of operand and requested scales must not turn a nonzero divisor into a division by zero error.

    An invalid requested scale raises TPZ5001 during execution before the zero divisor is classified. The operation never replaces an invalid scale with zero or reports that scale error as a successful Result.

    The receiver, divisor, scale and explicitly supplied mode expressions evaluate once in that order before their values are validated. The operation preserves both operands.

    Причина

    A division result needs an explicit decimal grid because a finite pair of decimals can have a nonterminating quotient. Rounding the exact quotient once avoids hidden precision loss. A recoverable zero divisor stays distinct from invalid configuration and from internal scale arithmetic.

    Distinguish exact and repeating quotients at the requested grid

    Ссылка
    main.tpzDistinguish exact and repeating quotients at the requested gridОткрыть песочницу →
    1. import std.decimal { Decimal }
    2. import std.test
    3. import std.io
    4. function show(result: Result<Decimal, string>) -> () {
    5. let value: Decimal = test.assertOk(result)
    6. io.writeLine("{value.toString()} {value.scale()}")
    7. }
    8. let one: Decimal = (1).toDecimal()
    9. let third: Result<Decimal, string> = one.div((3).toDecimal(), 6)
    10. let eighth: Result<Decimal, string> = one.div((8).toDecimal(), 2)
    11. let negativeTie: Result<Decimal, string> = (-1).toDecimal().div((8).toDecimal(), 2)
    12. let exact: Result<Decimal, string> = (100).toDecimal().div((4).toDecimal(), 4)
    13. let integerGrid: Result<Decimal, string> = (2).toDecimal().div((3).toDecimal(), 0)
    14. show(third)
    15. show(eighth)
    16. show(negativeTie)
    17. show(exact)
    18. show(integerGrid)
    Ожидаемый выводКод завершения 0
    0.333333 6
    0.12 2
    -0.12 2
    25 0
    1 0
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. 0.333333 6
    2. 0.12 2
    3. -0.12 2
    4. 25 0
    5. 1 0

    Apply every rounding mode to signed quotient ties

    Ссылка
    main.tpzApply every rounding mode to signed quotient tiesОткрыть песочницу →
    1. import std.decimal { Decimal, RoundingMode }
    2. import std.test
    3. import std.io
    4. function read(text: string) -> Decimal {
    5. let parsed: Option<Decimal> = Decimal.parse(text)
    6. let value: Decimal = test.assertSome(parsed)
    7. return value
    8. }
    9. function quotient(text: string, mode: RoundingMode) -> string {
    10. let value: Decimal = read(text)
    11. let result: Result<Decimal, string> = value.div((2).toDecimal(), 0, mode)
    12. let rounded: Decimal = test.assertOk(result)
    13. return rounded.toString()
    14. }
    15. let modes: Array<RoundingMode> = [RoundingMode.Down(), RoundingMode.Up(), RoundingMode.TowardZero(), RoundingMode.AwayFromZero(), RoundingMode.HalfUp(), RoundingMode.HalfEven()]
    16. for mode in (modes) {
    17. let a = quotient("5", mode)
    18. let b = quotient("7", mode)
    19. let c = quotient("-5", mode)
    20. let d = quotient("-7", mode)
    21. io.writeLine("{a} {b} {c} {d}")
    22. }
    Ожидаемый выводКод завершения 0
    2 3 -3 -4
    3 4 -2 -3
    2 3 -2 -3
    3 4 -3 -4
    3 4 -3 -4
    2 4 -2 -4
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. 2 3 -3 -4
    2. 3 4 -2 -3
    3. 2 3 -2 -3
    4. 3 4 -3 -4
    5. 3 4 -3 -4
    6. 2 4 -2 -4

    Return a recoverable error for every zero divisor

    Ссылка
    main.tpzReturn a recoverable error for every zero divisorОткрыть песочницу →
    1. import std.decimal { Decimal }
    2. import std.test
    3. import std.io
    4. function read(text: string) -> Decimal {
    5. let parsed: Option<Decimal> = Decimal.parse(text)
    6. let value: Decimal = test.assertSome(parsed)
    7. return value
    8. }
    9. let divisor: Decimal = read("-0.000")
    10. let numerators: Array<Decimal> = [(0).toDecimal(), (1).toDecimal()]
    11. for numerator in (numerators) {
    12. let result: Result<Decimal, string> = numerator.div(divisor, 2)
    13. match (result) {
    14. case Err(message) => io.writeLine(message)
    15. case Ok(_) => io.writeLine("accepted")
    16. }
    17. }
    18. io.writeLine(divisor.toString())
    Ожидаемый выводКод завершения 0
    Decimal.div: division by zero
    Decimal.div: division by zero
    0
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. Decimal.div: division by zero
    2. Decimal.div: division by zero
    3. 0

    Keep a zero quotient at the largest valid scale

    Ссылка
    main.tpzKeep a zero quotient at the largest valid scaleОткрыть песочницу →
    1. import std.decimal { Decimal }
    2. import std.test
    3. import std.io
    4. function read(text: string) -> Decimal {
    5. let parsed: Option<Decimal> = Decimal.parse(text)
    6. let value: Decimal = test.assertSome(parsed)
    7. return value
    8. }
    9. let divisor: Decimal = read("0.1")
    10. let result: Result<Decimal, string> = (0).toDecimal().div(divisor, 4294967295)
    11. match (result) {
    12. case Ok(value) => io.writeLine(value.toString())
    13. case Err(_) => io.writeLine("unexpected error")
    14. }
    Ожидаемый выводКод завершения 0
    0
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. 0

    Evaluate the receiver and division arguments once in order

    Ссылка
    main.tpzEvaluate the receiver and division arguments once in orderОткрыть песочницу →
    1. import std.decimal { Decimal, RoundingMode }
    2. import std.test
    3. import std.io
    4. function receiver() -> Decimal {
    5. io.writeLine("receiver")
    6. return (6).toDecimal()
    7. }
    8. function divisor() -> Decimal {
    9. io.writeLine("divisor")
    10. return (4).toDecimal()
    11. }
    12. function scale() -> int {
    13. io.writeLine("scale")
    14. return 1
    15. }
    16. function mode() -> RoundingMode {
    17. io.writeLine("mode")
    18. return RoundingMode.HalfEven()
    19. }
    20. let result: Result<Decimal, string> = receiver().div(divisor(), scale(), mode())
    21. let value: Decimal = test.assertOk(result)
    22. io.writeLine(value.toString())
    Ожидаемый выводКод завершения 0
    receiver
    divisor
    scale
    mode
    1.5
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. receiver
    2. divisor
    3. scale
    4. mode
    5. 1.5

    Reject an invalid scale before classifying a zero divisor

    Ссылка
    main.tpzReject an invalid scale before classifying a zero divisorОткрыть песочницу →
    1. import std.decimal { Decimal }
    2. import std.io
    3. let value: Decimal = (1).toDecimal()
    4. value.div((0).toDecimal(), -1)
    5. io.writeLine("after")
    Ожидаемый выводНенулевой код завершения
    Нет стандартного вывода.
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения run. Ненулевой код завершения.

    Reject an invalid scale before classifying a zero divisor

    Ссылка
    main.tpzReject an invalid scale before classifying a zero divisorОткрыть песочницу →
    1. import std.decimal { Decimal }
    2. import std.io
    3. let value: Decimal = (1).toDecimal()
    4. value.div((0).toDecimal(), 4294967296)
    5. io.writeLine("after")
    Ожидаемый выводНенулевой код завершения
    Нет стандартного вывода.
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Этап отклонения run. Ненулевой код завершения.

    Diagnostics

    Ссылка

    Runtime value guard →

    Меню

    Загрузка →