From 7345a14342ba90c947bbba3121604a57b24ddc8f Mon Sep 17 00:00:00 2001 From: "Arch D. Robison" Date: Fri, 20 Nov 2015 13:41:47 -0600 Subject: [PATCH] Add manual section about numerical conversions. --- doc/manual/mathematical-operations.rst | 69 ++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/doc/manual/mathematical-operations.rst b/doc/manual/mathematical-operations.rst index 64e6f1e223b37..fe8ee11f527b9 100644 --- a/doc/manual/mathematical-operations.rst +++ b/doc/manual/mathematical-operations.rst @@ -347,6 +347,73 @@ Control flow ``&&`` followed by ``||`` followed by ``?`` Assignments ``= += -= *= /= //= \= ^= ÷= %= |= &= $= <<= >>= >>>=`` and ``.+= .-= .*= ./= .//= .\= .^= .÷= .%=`` ================= ============================================================================================= +.. _man-numerical-conversions: + +Numerical Conversions +--------------------- + +Julia supports three forms of numerical conversion, which differ in their +handling of inexact conversions. + +- The notation ``T(x)`` or ``convert(T,x)`` converts ``x`` to a value of type ``T``. + + - If ``T`` is a floating-point type, the result is the nearest representable + value, which could be positive or negative infinity. + + - If ``T`` is an integer type, an ``InexactError`` is raised if ``x`` + is not representable by ``T``. + + +- ``x % T`` converts an integer ``x`` to a value of integer type ``T`` + congruent to ``x`` modulo ``2^n``, where ``n`` is the number of bits in ``T``. + In other words, the binary representation is truncated to fit. + +- The :ref:`man-rounding-functions` take a type ``T`` as an optional argument. + For example, ``round(Int,x)`` is a shorthand for ``Int(round(x))``. + +The following examples show the different forms. + +.. doctest:: + + julia> Int8(127) + 127 + + julia> Int8(128) + ERROR: InexactError() + in call at ./essentials.jl:58 + in eval at ./boot.jl:263 + + julia> Int8(127.0) + 127 + + julia> Int8(3.14) + ERROR: InexactError() + in call at ./essentials.jl:58 + in eval at ./boot.jl:263 + + julia> Int8(128.0) + ERROR: InexactError() + in call at ./essentials.jl:58 + in eval at ./boot.jl:263 + + julia> 127 % Int8 + 127 + + julia> 128 % Int8 + -128 + + julia> round(Int8,127.4) + 127 + + julia> round(Int8,127.6) + ERROR: InexactError() + in trunc at ./float.jl:357 + in round at ./float.jl:177 + in eval at ./boot.jl:263 + +See :ref:`man-conversion-and-promotion` for how to define your own +conversions and promotions. + .. _man-elementary-functions: Elementary Functions @@ -358,6 +425,8 @@ class of numerical values as permit sensible definitions, including integers, floating-point numbers, rationals, and complexes, wherever such definitions make sense. +.. _man-rounding-functions: + Rounding functions ~~~~~~~~~~~~~~~~~~