From 272625046e887aae103ff70f1cd3d35d4bc18462 Mon Sep 17 00:00:00 2001 From: Liam Jongsu Kim Date: Tue, 18 Aug 2015 16:14:54 +0900 Subject: [PATCH 1/3] =?UTF-8?q?Getting=20Started,=20Variables=20=EB=9D=84?= =?UTF-8?q?=EC=96=B4=EC=93=B0=EA=B8=B0=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/julia/doc/manual/getting-started.rst.txt | 84 ++++++++++---------- src/julia/doc/manual/variables.rst.txt | 48 +++++------ 2 files changed, 66 insertions(+), 66 deletions(-) diff --git a/src/julia/doc/manual/getting-started.rst.txt b/src/julia/doc/manual/getting-started.rst.txt index 8f1b429..87b7e74 100644 --- a/src/julia/doc/manual/getting-started.rst.txt +++ b/src/julia/doc/manual/getting-started.rst.txt @@ -5,17 +5,17 @@ -- Getting Started == ***************** == -++ 줄리아의 설치는 어렵지 않다. 미리 컴파일된 실행파일을 이용하거나, -++ 아니면 소스로부터 직접 컴파일하는 두가지 방법이 존재한다. -++ `http://julialang.org/downloads/ `_ 에서 +++ 줄리아의 설치는 어렵지 않다. 미리 컴파일된 실행파일을 이용하거나, +++ 아니면 소스로부터 직접 컴파일하는 두가지 방법이 존재한다. +++ `http://julialang.org/downloads/ `_ 에서 ++ 알려주는 방법에 따라 Julia를 다운로드하고 설치하면 된다. -- Julia installation is straightforward, whether using precompiled -- binaries or compiling from source. Download and install Julia by -- following the instructions at -- `http://julialang.org/downloads/ `_. == -++ Julia를 처음 접할 때는 대화형 실행 환경을 통해서 시작하는 것이 -++ 가장 쉽게 Julia를 익힐 수 있는 방법이다. +++ Julia를 처음 접할 때는 대화형 실행 환경을 통해서 시작하는 것이 +++ 가장 쉽게 Julia를 익힐 수 있는 방법이다. ++ 대화형 실행 환경은 단순히 Julia 실행파일을 더블 클릭하거나, 명령창에서 ++ ``julia`` 명령어를 입력하여 실행할 수 있다. -- The easiest way to learn and experiment with Julia is by starting an @@ -41,18 +41,18 @@ == julia> ans == 3 == -++ 대화형 실행 환경을 종료하기 위해서는 ``^D`` 를 입력하거나 -++ (컨트롤 키와 ``d`` 키를 ++ 함께 누른다.) -++ ``quit()`` 를 대화형 실행 환경 입력창에 타이핑한다. -++ 대화형 실행 환경을 실행하면, 위와 같이 ``julia`` 배너가 보여지고, +++ 대화형 실행 환경을 종료하기 위해서는 ``^D`` 를 입력하거나 +++ (컨트롤 키와 ``d`` 키를 ++ 함께 누른다.) +++ ``quit()`` 를 대화형 실행 환경 입력창에 타이핑한다. +++ 대화형 실행 환경을 실행하면, 위와 같이 ``julia`` 배너가 보여지고, ++ 커서창이 사용자의 입력을 기다리며 깜빡이고 있다. 사용자가 -++ ``1 + 2`` 와 같은 표현식을 입력한 뒤, 엔터 버튼을 누르는 순간, -++ Julia는 표현식을 평가하고 그 결과를 보여준다. +++ ``1 + 2`` 와 같은 표현식을 입력한 뒤, 엔터 버튼을 누르는 순간, +++ Julia는 표현식을 평가하고 그 결과를 보여준다. ++ 만약 사용자가 입력한 표현식이 세미콜론(;)으로 끝난다면, -++ 대화형 실행 환경은 결과를 바로 보여주지 않는다. +++ 대화형 실행 환경은 결과를 바로 보여주지 않는다. ++ 대신에 ``ans`` 라는 변수가 결과를 보여주든 보여주지 않든 ++ 가장 마지막으로 계산된 표현식의 결과를 저장하고 있다. -++ ``ans`` 변수는 대화형 실행 환경에서만 존재하며, 다른 방식으로 동작하는 +++ ``ans`` 변수는 대화형 실행 환경에서만 존재하며, 다른 방식으로 동작하는 ++ Julia 코드 상에서는 나타나지 않는다. -- To exit the interactive session, type ``^D`` — the control key -- together with the ``d`` key or type ``quit()``. When run in interactive @@ -65,14 +65,14 @@ -- it is shown or not. The ``ans`` variable is only bound in interactive -- sessions, not when Julia code is run in other ways. == -++ ``file.ji`` 라는 소스 파일에 저장되어 있는 표현식을 계산하기 위해서는, +++ ``file.ji`` 라는 소스 파일에 저장되어 있는 표현식을 계산하기 위해서는, ++ ``include("file.ji")`` 와 같이 입력한다. -- To evaluate expressions written in a source file ``file.jl``, write -- ``include("file.jl")``. == -++ 대화형 실행 환경을 이용하지 않고 -++ 파일에 저장되어 있는 소스 코드를 실행하기 위해서는, -++ 소스 코드 파일 이름을 julia 명령어의 첫번째 매개 변수로 넣어서 실행한다. +++ 대화형 실행 환경을 이용하지 않고 +++ 파일에 저장되어 있는 소스 코드를 실행하기 위해서는, +++ 소스 코드 파일 이름을 julia 명령어의 첫번째 매개 변수로 넣어서 실행한다. -- To run code in a file non-interactively, you can give it as the first -- argument to the julia command:: == @@ -80,14 +80,14 @@ ++ == $ julia script.jl arg1 arg2... == -++ 예제와 같이 julia 실행 명령 뒤에 오는 매개변수들은 -++ 전역 상수 ``ARGS`` 라고 불리우는 -++ ``script.ji`` 프로그램의 명령줄 인자로 작동한다. -++ ``ARGS`` 는 이 뿐만이 아니라 -++ ``-e`` 옵션을 통해서 julia 스크립트를 실행할 때도 설정할 수 있다. -++ (아래의 ``julia`` 도움말을 보도록 하자.) -++ 예를 들어, 단순히 스크립트에 주어진 명령줄 인자를 출력할 때는 -++ 다음과 같이 입력하면 된다. +++ 예제와 같이 julia 실행 명령 뒤에 오는 매개변수들은 +++ 전역 상수 ``ARGS`` 라고 불리우는 +++ ``script.ji`` 프로그램의 명령줄 인자로 작동한다. +++ ``ARGS`` 는 이 뿐만이 아니라 +++ ``-e`` 옵션을 통해서 julia 스크립트를 실행할 때도 설정할 수 있다. +++ (아래의 ``julia`` 도움말을 보도록 하자.) +++ 예를 들어, 단순히 스크립트에 주어진 명령줄 인자를 출력할 때는 +++ 다음과 같이 입력하면 된다. -- As the example implies, the following command-line arguments to julia -- are taken as command-line arguments to the program ``script.jl``, passed -- in the global constant ``ARGS``. ``ARGS`` is also set when script code @@ -101,7 +101,7 @@ == foo == bar -- -++ 아니면 저 코드를 스크립트 파일에 넣고 실행시켜도 가능하다. +++ 아니면 저 코드를 스크립트 파일에 넣고 실행시켜도 가능하다. -- Or you could put that code into a script and run it:: == ++ .. code-block:: shell @@ -111,21 +111,21 @@ == foo == bar == -++ Julia는 ``-p`` 옵션이나 ``--machinefile`` 옵션을 이용하여 -++ 병렬 환경에서 실행시킬 수 있다. -++ ``-p n`` 옵션은 n개의 worker 프로세스를 생성하지만, -++ ``--machinefile file`` 옵션은 file의 각 행에 지정된 노드마다 -++ worker를 생성한다. -++ ``file`` 에 지정된 노드(machine)들은 ``ssh`` 로그인을 통해 -++ 패스워드가 필요없이 실행할 수 있어야 하며, -++ Julia는 현재 호스트와 같은 경로에 설치가 되어 있어야 한다. -++ ``file`` 에 작성되는 노드는 +++ Julia는 ``-p`` 옵션이나 ``--machinefile`` 옵션을 이용하여 +++ 병렬 환경에서 실행시킬 수 있다. +++ ``-p n`` 옵션은 n개의 worker 프로세스를 생성하지만, +++ ``--machinefile file`` 옵션은 file의 각 행에 지정된 노드마다 +++ worker를 생성한다. +++ ``file`` 에 지정된 노드(machine)들은 ``ssh`` 로그인을 통해 +++ 패스워드가 필요없이 실행할 수 있어야 하며, +++ Julia는 현재 호스트와 같은 경로에 설치가 되어 있어야 한다. +++ ``file`` 에 작성되는 노드는 ++ ``[count*][user@]host[:port] [bind_addr[:port]]`` -++ 와 같은 형식으로 작성한다. -++ ``user`` 는 현재 user id를 나타내고, ``port`` 는 기본 ssh port, -++ ``count`` 는 각 노드당 생성하는 worker의 개수 (기본값 : 1) -++ ``bin-to bind_addr[:port]`` 은 선택적인 옵션으로 -++ 다른 worker들이 현재의 worker로 연결하기 위해 필요한 +++ 와 같은 형식으로 작성한다. +++ ``user`` 는 현재 user id를 나타내고, ``port`` 는 기본 ssh port, +++ ``count`` 는 각 노드당 생성하는 worker의 개수 (기본값 : 1) +++ ``bin-to bind_addr[:port]`` 은 선택적인 옵션으로 +++ 다른 worker들이 현재의 worker로 연결하기 위해 필요한 ++ 특정 ip 주소와 포트를 지정한다. -- Julia can be started in parallel mode with either the ``-p`` or the -- ``--machinefile`` options. ``-p n`` will launch an additional ``n`` worker @@ -140,7 +140,7 @@ -- connect to this worker. == == -++ 만약 julia가 실행할 때마다 실행되는 코드가 있다면, +++ 만약 julia가 실행할 때마다 실행되는 코드가 있다면, ++ 그 코드를 ``~/.juliarc.ji`` 에 넣으면 된다. -- If you have code that you want executed whenever julia is run, you can -- put it in ``~/.juliarc.jl``: @@ -163,7 +163,7 @@ -- -- \end{CJK*} == -++ ``perl`` 이나 ``ruby`` 와 같이, +++ ``perl`` 이나 ``ruby`` 와 같이, ++ Julia 코드를 실행하고 옵션을 지정하는 방법은 다음과 같이 여러가지가 있다. -- There are various ways to run Julia code and provide options, similar to -- those available for the ``perl`` and ``ruby`` programs:: diff --git a/src/julia/doc/manual/variables.rst.txt b/src/julia/doc/manual/variables.rst.txt index ae41f87..37672e9 100644 --- a/src/julia/doc/manual/variables.rst.txt +++ b/src/julia/doc/manual/variables.rst.txt @@ -5,7 +5,7 @@ == *********** == ++ Julia에서 변수는 값에 연관된 (혹은 한정되는) 이름을 말한다. -++ 변수는 나중에 사용할 용도로 값(예를 들면, 수학 연산을 통해 얻어진 값)을 +++ 변수는 나중에 사용할 용도로 값(예를 들면, 수학 연산을 통해 얻어진 값)을 ++ 저장할 때 유용하다. 예를 들면: -- A variable, in Julia, is a name associated (or bound) to a value. It's useful when you want to store a value (that you obtained after some math, for example) for later use. For example: == @@ -31,9 +31,9 @@ == julia> x = "Hello World!" == "Hello World!" == -++ Julia는 변수의 이름을 지정하는데 있어서 매우 유연하다. -++ 변수의 이름은 대소문자를 구별하며, 어떤 특정한 의미를 부여하지 않는다. -++ (변수의 이름이 특별하다고 해서 +++ Julia는 변수의 이름을 지정하는데 있어서 매우 유연하다. +++ 변수의 이름은 대소문자를 구별하며, 어떤 특정한 의미를 부여하지 않는다. +++ (변수의 이름이 특별하다고 해서 ++ Julia가 변수들 다른 방식으로 다루지 않는다) -- Julia provides an extremely flexible system for naming variables. -- Variable names are case-sensitive, and have no semantic meaning (that is, @@ -79,12 +79,12 @@ == julia> 안녕하세요 = "Hello" == "Hello" == -++ Julia 대화형 실행환경 혹은 다른 Julia 편집 환경에서는, +++ Julia 대화형 실행환경 혹은 다른 Julia 편집 환경에서는, ++ 유니코드로 지정되어 있는 -++ 백슬래시로 표현되는 LaTex 기호들을 tab과 함께 입력할 수 있다. +++ 백슬래시로 표현되는 LaTex 기호들을 tab과 함께 입력할 수 있다. ++ 예를 들면, 변수명 ``δ``\ 는 ``\delta``-\ *tab*\ 로, -++ ``α̂₂`` 는 -++ ``\alpha``-\ *tab*\ -``\hat``-\ *tab*\ -``\_2``-\ *tab*\ 로 +++ ``α̂₂`` 는 +++ ``\alpha``-\ *tab*\ -``\hat``-\ *tab*\ -``\_2``-\ *tab*\ 로 ++ 표현할 수 있다. -- In the Julia REPL and several other Julia editing environments, you -- can type many Unicode math symbols by typing the backslashed LaTeX symbol @@ -126,15 +126,15 @@ -- Allowed Variable Names -- ====================== == -++ 변수명은 영문 대소문자 (A-Z 혹은 a-z), 밑줄, +++ 변수명은 영문 대소문자 (A-Z 혹은 a-z), 밑줄, ++ 혹은 00A0이상의 코드표를 지니는 유니코드 글자로 시작해야한다; -++ 자세히 이야기하면, `Unicode character categories`_ -++ Lu/Ll/Lt/Lm/Lo/Nl (글자), Sc/So (통화 및 다른 기호), -++ 그리고 다른 몇 가지의 문자같은 기호들도 (예를 들어 Sm 수학기호) 허용한다. +++ 자세히 이야기하면, `Unicode character categories`_ +++ Lu/Ll/Lt/Lm/Lo/Nl (글자), Sc/So (통화 및 다른 기호), +++ 그리고 다른 몇 가지의 문자같은 기호들도 (예를 들어 Sm 수학기호) 허용한다. ++ 첫 글자 다음은 !(느낌표)와 ++ 숫자 (0-9와 Nd/No 카테고리에 포함되는 문자들) 뿐만 아니라, -++ 다른 유니코드 문자들도 변수명으로 허용한다:여기에는 변수명 허용범위에 -++ 발음기호 및 다른 수정기호(Mn/Mc/Me/Sk), +++ 다른 유니코드 문자들도 변수명으로 허용한다:여기에는 변수명 허용범위에 +++ 발음기호 및 다른 수정기호(Mn/Mc/Me/Sk), ++ 몇몇 구두점 접속사 (Pc 카테고리), prime 기호들, ++ 그리고 몇 가지 다른 기호들을 포함한다는 것을 뜻한다. -- Variable names must begin with a letter (A-Z or a-z), underscore, or a @@ -148,15 +148,15 @@ == == .. _Unicode character categories: http://www.fileformat.info/info/unicode/category/index.htm == -++ ``+``\ 와 같은 기호들을 변수명으로 허용되지만, -++ Julia가 특별한 방식으로 파싱(parsing)한다. +++ ``+``\ 와 같은 기호들을 변수명으로 허용되지만, +++ Julia가 특별한 방식으로 파싱(parsing)한다. ++ 어떤 경우에는, 연산자들은 일반적인 변수처럼 취급될 수도 있다; -++ 예를 들면 ``(+)``\ 는 덧셈 함수처럼 인식되어, -++ ``(+) = f``\ 와 같이 정의할 수 있다. -++ Sm 카테고리에 있는 대부분의 유니코드 중위기호(infix)들은 -++ 중위 연산자(infix operator)로 +++ 예를 들면 ``(+)``\ 는 덧셈 함수처럼 인식되어, +++ ``(+) = f``\ 와 같이 정의할 수 있다. +++ Sm 카테고리에 있는 대부분의 유니코드 중위기호(infix)들은 +++ 중위 연산자(infix operator)로 ++ 파싱(parsing)되며 사용자가 새롭게 정의할 수 있다. -++ (예를 들어 ``const ⊗ = kron``\ 와 같이 +++ (예를 들어 ``const ⊗ = kron``\ 와 같이 ++ 중위 크로네커 곱셈을 ``⊗``\ 로 정의할 수 있다.) -- Operators like ``+`` are also valid identifiers, but are parsed specially. In -- some contexts, operators can be used just like variables; for example @@ -190,15 +190,15 @@ == ++ - 변수명은 소문자로 한다. ++ - 변수명 내의 단어 구분은 밑줄로써 표현될 수 있지만, -++ 밑줄(``'_'``)은 최대한 안쓰는 것이 좋다. +++ 밑줄(``'_'``)은 최대한 안쓰는 것이 좋다. ++ (단어가 구분이 안되서 변수명을 읽기 힘들때만 밑줄을 쓰도록 한다.) -++ - ``Type``\ 이름은 대문자로 시작하고 +++ - ``Type``\ 이름은 대문자로 시작하고 ++ 단어 구분은 밑줄 대신에 대문자로 시작하는 ++ 카멜표기법을 따른다. ++ - ``function``\ 과 ``macro``\ 의 이름은 밑줄 없는 소문자가 좋다. ++ - 매개변수를 수정하는 함수들의 이름은 ``!``\ 로 끝내는 것이 좋다. ++ 이는 "mutation" 함수나 "in-place" 함수라고 불리우는 것인데, -++ 이 함수들은 실행했을 때 단순히 어떤 값을 리턴하는 것이 아니라, +++ 이 함수들은 실행했을 때 단순히 어떤 값을 리턴하는 것이 아니라, ++ 입력값(매개변수)를 변화시키기 때문이다. -- - Names of variables are in lower case. -- - Word separation can be indicated by underscores (``'_'``), but use of From 0cf285a11fadc5cd846ba5ef33cca0825c52ad5a Mon Sep 17 00:00:00 2001 From: Liam Jongsu Kim Date: Tue, 18 Aug 2015 17:21:51 +0900 Subject: [PATCH 2/3] =?UTF-8?q?=EB=B2=84=EA=B7=B8=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/julia/doc/manual/getting-started.rst.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/julia/doc/manual/getting-started.rst.txt b/src/julia/doc/manual/getting-started.rst.txt index 87b7e74..8b7fd47 100644 --- a/src/julia/doc/manual/getting-started.rst.txt +++ b/src/julia/doc/manual/getting-started.rst.txt @@ -100,7 +100,7 @@ == $ julia -e 'for x in ARGS; println(x); end' foo bar == foo == bar --- +== ++ 아니면 저 코드를 스크립트 파일에 넣고 실행시켜도 가능하다. -- Or you could put that code into a script and run it:: == From e6b8969b4ce95970be8471bf295df1685a8031e4 Mon Sep 17 00:00:00 2001 From: Liam Jongsu Kim Date: Wed, 19 Aug 2015 01:23:33 +0900 Subject: [PATCH 3/3] =?UTF-8?q?Integers=20and=20Floating=20Point=20Numbers?= =?UTF-8?q?=20=EB=B2=88=EC=97=AD=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../integers-and-floating-point-numbers.rst | 781 ++++++++++++ scripts/Setting.jl | 1 + ...ntegers-and-floating-point-numbers.rst.txt | 1073 +++++++++++++++++ 3 files changed, 1855 insertions(+) create mode 100644 codex/julia/doc/manual/integers-and-floating-point-numbers.rst create mode 100644 src/julia/doc/manual/integers-and-floating-point-numbers.rst.txt diff --git a/codex/julia/doc/manual/integers-and-floating-point-numbers.rst b/codex/julia/doc/manual/integers-and-floating-point-numbers.rst new file mode 100644 index 0000000..8bb7e1c --- /dev/null +++ b/codex/julia/doc/manual/integers-and-floating-point-numbers.rst @@ -0,0 +1,781 @@ +.. _man-integers-and-floating-point-numbers: + +.. currentmodule:: Base + +************************************* + Integers and Floating-Point Numbers +************************************* + +Integers and floating-point values are the basic building blocks of +arithmetic and computation. Built-in representations of such values are +called numeric primitives, while representations of integers and +floating-point numbers as immediate values in code are known as numeric +literals. For example, ``1`` is an integer literal, while ``1.0`` is a +floating-point literal; their binary in-memory representations as +objects are numeric primitives. + +Julia provides a broad range of primitive numeric types, and a full complement +of arithmetic and bitwise operators as well as standard mathematical functions +are defined over them. These map directly onto numeric types and operations +that are natively supported on modern computers, thus allowing Julia to take +full advantage of computational resources. Additionally, Julia provides +software support for :ref:`man-arbitrary-precision-arithmetic`, which can +handle operations on numeric values that cannot be represented effectively in +native hardware representations, but at the cost of relatively slower +performance. + +The following are Julia's primitive numeric types: + +- **Integer types:** + +================ ======= ============== ============== ================== +Type Signed? Number of bits Smallest value Largest value +---------------- ------- -------------- -------------- ------------------ +:class:`Int8` ✓ 8 -2^7 2^7 - 1 +:class:`UInt8` 8 0 2^8 - 1 +:class:`Int16` ✓ 16 -2^15 2^15 - 1 +:class:`UInt16` 16 0 2^16 - 1 +:class:`Int32` ✓ 32 -2^31 2^31 - 1 +:class:`UInt32` 32 0 2^32 - 1 +:class:`Int64` ✓ 64 -2^63 2^63 - 1 +:class:`UInt64` 64 0 2^64 - 1 +:class:`Int128` ✓ 128 -2^127 2^127 - 1 +:class:`UInt128` 128 0 2^128 - 1 +:class:`Bool` N/A 8 ``false`` (0) ``true`` (1) +================ ======= ============== ============== ================== + +- **Floating-point types:** + +================ ========= ============== +Type Precision Number of bits +---------------- --------- -------------- +:class:`Float16` half_ 16 +:class:`Float32` single_ 32 +:class:`Float64` double_ 64 +================ ========= ============== + +.. _half: https://en.wikipedia.org/wiki/Half-precision_floating-point_format +.. _single: https://en.wikipedia.org/wiki/Single_precision_floating-point_format +.. _double: https://en.wikipedia.org/wiki/Double_precision_floating-point_format + +Additionally, full support for :ref:`man-complex-and-rational-numbers` is built +on top of these primitive numeric types. All numeric types interoperate +naturally without explicit casting, thanks to a flexible, user-extensible +:ref:`type promotion system `. + +Integers +-------- + +Literal integers are represented in the standard manner: + +.. doctest:: + + julia> 1 + 1 + + julia> 1234 + 1234 + +The default type for an integer literal depends on whether the target +system has a 32-bit architecture or a 64-bit architecture:: + + # 32-bit system: + julia> typeof(1) + Int32 + + # 64-bit system: + julia> typeof(1) + Int64 + +The Julia internal variable :const:`WORD_SIZE` indicates whether the target system +is 32-bit or 64-bit.:: + + # 32-bit system: + julia> WORD_SIZE + 32 + + # 64-bit system: + julia> WORD_SIZE + 64 + +Julia also defines the types :class:`Int` and :class:`UInt`, which are aliases for the +system's signed and unsigned native integer types respectively.:: + + # 32-bit system: + julia> Int + Int32 + julia> UInt + UInt32 + + + # 64-bit system: + julia> Int + Int64 + julia> UInt + UInt64 + +Larger integer literals that cannot be represented using only 32 bits +but can be represented in 64 bits always create 64-bit integers, +regardless of the system type:: + + # 32-bit or 64-bit system: + julia> typeof(3000000000) + Int64 + +Unsigned integers are input and output using the ``0x`` prefix and hexadecimal +(base 16) digits ``0-9a-f`` (the capitalized digits ``A-F`` also work for input). +The size of the unsigned value is determined by the number of hex digits used: + +.. doctest:: + + julia> 0x1 + 0x01 + + julia> typeof(ans) + UInt8 + + julia> 0x123 + 0x0123 + + julia> typeof(ans) + UInt16 + + julia> 0x1234567 + 0x01234567 + + julia> typeof(ans) + UInt32 + + julia> 0x123456789abcdef + 0x0123456789abcdef + + julia> typeof(ans) + UInt64 + +This behavior is based on the observation that when one uses unsigned +hex literals for integer values, one typically is using them to +represent a fixed numeric byte sequence, rather than just an integer +value. + +Recall that the variable :data:`ans` is set to the value of the last expression +evaluated in an interactive session. This does not occur when Julia code is +run in other ways. + +Binary and octal literals are also supported: + +.. doctest:: + + julia> 0b10 + 0x02 + + julia> typeof(ans) + UInt8 + + julia> 0o10 + 0x08 + + julia> typeof(ans) + UInt8 + +The minimum and maximum representable values of primitive numeric types +such as integers are given by the :func:`typemin` and :func:`typemax` functions: + +.. doctest:: + + julia> (typemin(Int32), typemax(Int32)) + (-2147483648,2147483647) + + julia> for T in [Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128] + println("$(lpad(T,7)): [$(typemin(T)),$(typemax(T))]") + end + Int8: [-128,127] + Int16: [-32768,32767] + Int32: [-2147483648,2147483647] + Int64: [-9223372036854775808,9223372036854775807] + Int128: [-170141183460469231731687303715884105728,170141183460469231731687303715884105727] + UInt8: [0,255] + UInt16: [0,65535] + UInt32: [0,4294967295] + UInt64: [0,18446744073709551615] + UInt128: [0,340282366920938463463374607431768211455] + +The values returned by :func:`typemin` and :func:`typemax` are always of the +given argument type. (The above expression uses several features we have +yet to introduce, including :ref:`for loops `, +:ref:`man-strings`, and :ref:`man-string-interpolation`, +but should be easy enough to understand for users with some existing +programming experience.) + + +Overflow behavior +~~~~~~~~~~~~~~~~~ + +In Julia, exceeding the maximum representable value of a given type results in +a wraparound behavior: + +.. doctest:: + + julia> x = typemax(Int64) + 9223372036854775807 + + julia> x + 1 + -9223372036854775808 + + julia> x + 1 == typemin(Int64) + true + +Thus, arithmetic with Julia integers is actually a form of `modular arithmetic +`_. This reflects the +characteristics of the underlying arithmetic of integers as implemented on +modern computers. In applications where overflow is possible, explicit checking +for wraparound produced by overflow is essential; otherwise, the ``BigInt`` type +in :ref:`man-arbitrary-precision-arithmetic` is recommended instead. + +Division errors +~~~~~~~~~~~~~~~ + +Integer division (the ``div`` function) has two exceptional cases: dividing by +zero, and dividing the lowest negative number (:func:`typemin`) by -1. Both of +these cases throw a :exc:`DivideError`. The remainder and modulus functions +(``rem`` and ``mod``) throw a :exc:`DivideError` when their second argument is +zero. + +Floating-Point Numbers +---------------------- + +Literal floating-point numbers are represented in the standard formats: + +.. doctest:: + + julia> 1.0 + 1.0 + + julia> 1. + 1.0 + + julia> 0.5 + 0.5 + + julia> .5 + 0.5 + + julia> -1.23 + -1.23 + + julia> 1e10 + 1.0e10 + + julia> 2.5e-4 + 0.00025 + +The above results are all ``Float64`` values. Literal ``Float32`` values can +be entered by writing an ``f`` in place of ``e``: + +.. doctest:: + + julia> 0.5f0 + 0.5f0 + + julia> typeof(ans) + Float32 + + julia> 2.5f-4 + 0.00025f0 + +Values can be converted to ``Float32`` easily: + +.. doctest:: + + julia> Float32(-1.5) + -1.5f0 + + julia> typeof(ans) + Float32 + +Hexadecimal floating-point literals are also valid, but only as ``Float64`` values: + +.. doctest:: + + julia> 0x1p0 + 1.0 + + julia> 0x1.8p3 + 12.0 + + julia> 0x.4p-1 + 0.125 + + julia> typeof(ans) + Float64 + +Half-precision floating-point numbers are also supported (``Float16``), but +only as a storage format. In calculations they'll be converted to ``Float32``: + +.. doctest:: + + julia> sizeof(Float16(4.)) + 2 + + julia> 2*Float16(4.) + 8.0f0 + +The underscore ``_`` can be used as digit separator: + +.. doctest:: + + julia> 10_000, 0.000_000_005, 0xdead_beef, 0b1011_0010 + (10000,5.0e-9,0xdeadbeef,0xb2) + +Floating-point zero +~~~~~~~~~~~~~~~~~~~ + +Floating-point numbers have `two zeros +`_, positive zero and negative zero. +They are equal to each other but have different binary representations, as can +be seen using the ``bits`` function: : + +.. doctest:: + + julia> 0.0 == -0.0 + true + + julia> bits(0.0) + "0000000000000000000000000000000000000000000000000000000000000000" + + julia> bits(-0.0) + "1000000000000000000000000000000000000000000000000000000000000000" + +.. _man-special-floats: + +Special floating-point values +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +There are three specified standard floating-point values that do not +correspond to any point on the real number line: + +=========== =========== =========== ================= ================================================================= +Special value Name Description +----------------------------------- ----------------- ----------------------------------------------------------------- +``Float16`` ``Float32`` ``Float64`` +=========== =========== =========== ================= ================================================================= +``Inf16`` ``Inf32`` ``Inf`` positive infinity a value greater than all finite floating-point values +``-Inf16`` ``-Inf32`` ``-Inf`` negative infinity a value less than all finite floating-point values +``NaN16`` ``NaN32`` ``NaN`` not a number a value not ``==`` to any floating-point value (including itself) +=========== =========== =========== ================= ================================================================= + +For further discussion of how these non-finite floating-point values are +ordered with respect to each other and other floats, see +:ref:`man-numeric-comparisons`. By the +`IEEE 754 standard `_, these +floating-point values are the results of certain arithmetic operations: + +.. doctest:: + + julia> 1/Inf + 0.0 + + julia> 1/0 + Inf + + julia> -5/0 + -Inf + + julia> 0.000001/0 + Inf + + julia> 0/0 + NaN + + julia> 500 + Inf + Inf + + julia> 500 - Inf + -Inf + + julia> Inf + Inf + Inf + + julia> Inf - Inf + NaN + + julia> Inf * Inf + Inf + + julia> Inf / Inf + NaN + + julia> 0 * Inf + NaN + +The :func:`typemin` and :func:`typemax` functions also apply to floating-point +types: + +.. doctest:: + + julia> (typemin(Float16),typemax(Float16)) + (-Inf16,Inf16) + + julia> (typemin(Float32),typemax(Float32)) + (-Inf32,Inf32) + + julia> (typemin(Float64),typemax(Float64)) + (-Inf,Inf) + + +Machine epsilon +~~~~~~~~~~~~~~~ + +Most real numbers cannot be represented exactly with floating-point numbers, +and so for many purposes it is important to know the distance between two +adjacent representable floating-point numbers, which is often known as +`machine epsilon `_. + +Julia provides :func:`eps`, which gives the distance between ``1.0`` +and the next larger representable floating-point value: + +.. doctest:: + + julia> eps(Float32) + 1.1920929f-7 + + julia> eps(Float64) + 2.220446049250313e-16 + + julia> eps() # same as eps(Float64) + 2.220446049250313e-16 + +These values are ``2.0^-23`` and ``2.0^-52`` as ``Float32`` and ``Float64`` +values, respectively. The :func:`eps` function can also take a +floating-point value as an argument, and gives the absolute difference +between that value and the next representable floating point value. That +is, ``eps(x)`` yields a value of the same type as ``x`` such that +``x + eps(x)`` is the next representable floating-point value larger +than ``x``: + +.. doctest:: + + julia> eps(1.0) + 2.220446049250313e-16 + + julia> eps(1000.) + 1.1368683772161603e-13 + + julia> eps(1e-27) + 1.793662034335766e-43 + + julia> eps(0.0) + 5.0e-324 + +The distance between two adjacent representable floating-point numbers is not +constant, but is smaller for smaller values and larger for larger values. In +other words, the representable floating-point numbers are densest in the real +number line near zero, and grow sparser exponentially as one moves farther away +from zero. By definition, ``eps(1.0)`` is the same as ``eps(Float64)`` since +``1.0`` is a 64-bit floating-point value. + +Julia also provides the :func:`nextfloat` and :func:`prevfloat` functions which return +the next largest or smallest representable floating-point number to the +argument respectively: : + +.. doctest:: + + julia> x = 1.25f0 + 1.25f0 + + julia> nextfloat(x) + 1.2500001f0 + + julia> prevfloat(x) + 1.2499999f0 + + julia> bits(prevfloat(x)) + "00111111100111111111111111111111" + + julia> bits(x) + "00111111101000000000000000000000" + + julia> bits(nextfloat(x)) + "00111111101000000000000000000001" + +This example highlights the general principle that the adjacent representable +floating-point numbers also have adjacent binary integer representations. + +Rounding modes +~~~~~~~~~~~~~~ + +If a number doesn't have an exact floating-point representation, it must be +rounded to an appropriate representable value, however, if wanted, the manner +in which this rounding is done can be changed according to the rounding modes +presented in the `IEEE 754 standard `_:: + + + julia> 1.1 + 0.1 + 1.2000000000000002 + + julia> with_rounding(Float64,RoundDown) do + 1.1 + 0.1 + end + 1.2 + +The default mode used is always :const:`RoundNearest`, which rounds to the nearest +representable value, with ties rounded towards the nearest value with an even +least significant bit. + +.. warning:: Rounding is generally only correct for basic arithmetic functions + (:func:`+`, :func:`-`, :func:`*`, :func:`/` and :func:`sqrt`) and + type conversion operations. Many other functions assume the + default :const:`RoundNearest` mode is set, and can give erroneous + results when operating under other rounding modes. + +Background and References +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Floating-point arithmetic entails many subtleties which can be surprising to +users who are unfamiliar with the low-level implementation details. However, +these subtleties are described in detail in most books on scientific +computation, and also in the following references: + +- The definitive guide to floating point arithmetic is the `IEEE 754-2008 + Standard `_; + however, it is not available for free online. +- For a brief but lucid presentation of how floating-point numbers are + represented, see John D. Cook's `article + `_ + on the subject as well as his `introduction + `_ + to some of the issues arising from how this representation differs in + behavior from the idealized abstraction of real numbers. +- Also recommended is Bruce Dawson's `series of blog posts on floating-point + numbers `_. +- For an excellent, in-depth discussion of floating-point numbers and issues of + numerical accuracy encountered when computing with them, see David Goldberg's + paper `What Every Computer Scientist Should Know About Floating-Point + Arithmetic + `_. +- For even more extensive documentation of the history of, rationale for, + and issues with floating-point numbers, as well as discussion of many other + topics in numerical computing, see the `collected writings + `_ of `William Kahan + `_, commonly known as the "Father + of Floating-Point". Of particular interest may be `An Interview with the Old + Man of Floating-Point + `_. + +.. _man-arbitrary-precision-arithmetic: + +Arbitrary Precision Arithmetic +------------------------------ + +To allow computations with arbitrary-precision integers and floating point numbers, +Julia wraps the `GNU Multiple Precision Arithmetic Library (GMP) `_ and the `GNU MPFR Library `_, respectively. +The :class:`BigInt` and :class:`BigFloat` types are available in Julia for arbitrary precision +integer and floating point numbers respectively. + +Constructors exist to create these types from primitive numerical types, and +:func:`parse` can be use to construct them from :class:`AbstractString`\ s. Once +created, they participate in arithmetic with all other numeric types thanks to +Julia's +:ref:`type promotion and conversion mechanism `: + +.. doctest:: + + julia> BigInt(typemax(Int64)) + 1 + 9223372036854775808 + + julia> parse(BigInt, "123456789012345678901234567890") + 1 + 123456789012345678901234567891 + + julia> parse(BigFloat, "1.23456789012345678901") + 1.234567890123456789010000000000000000000000000000000000000000000000000000000004 + + julia> BigFloat(2.0^66) / 3 + 2.459565876494606882133333333333333333333333333333333333333333333333333333333344e+19 + + julia> factorial(BigInt(40)) + 815915283247897734345611269596115894272000000000 + +However, type promotion between the primitive types above and +:class:`BigInt`/:class:`BigFloat` is not automatic and must be explicitly stated. + +.. doctest:: + + julia> x = typemin(Int64) + -9223372036854775808 + + julia> x = x - 1 + 9223372036854775807 + + julia> typeof(x) + Int64 + + julia> y = BigInt(typemin(Int64)) + -9223372036854775808 + + julia> y = y - 1 + -9223372036854775809 + + julia> typeof(y) + Base.GMP.BigInt + +The default precision (in number of bits of the significand) and +rounding mode of :class:`BigFloat` operations can be changed globally +by calling :func:`set_bigfloat_precision` and +:func:`set_rounding`, and all further calculations will take +these changes in account. Alternatively, the precision or the +rounding can be changed only within the execution of a particular +block of code by :func:`with_bigfloat_precision` or +:func:`with_rounding`: + +.. doctest:: + + julia> with_rounding(BigFloat,RoundUp) do + BigFloat(1) + parse(BigFloat, "0.1") + end + 1.100000000000000000000000000000000000000000000000000000000000000000000000000003 + + julia> with_rounding(BigFloat,RoundDown) do + BigFloat(1) + parse(BigFloat, "0.1") + end + 1.099999999999999999999999999999999999999999999999999999999999999999999999999986 + + julia> with_bigfloat_precision(40) do + BigFloat(1) + parse(BigFloat, "0.1") + end + 1.1000000000004 + + +.. _man-numeric-literal-coefficients: + +Numeric Literal Coefficients +---------------------------- + +To make common numeric formulas and expressions clearer, Julia allows +variables to be immediately preceded by a numeric literal, implying +multiplication. This makes writing polynomial expressions much cleaner: + +.. doctest:: + + julia> x = 3 + 3 + + julia> 2x^2 - 3x + 1 + 10 + + julia> 1.5x^2 - .5x + 1 + 13.0 + +It also makes writing exponential functions more elegant: + +.. doctest:: + + julia> 2^2x + 64 + +The precedence of numeric literal coefficients is the same as that of unary +operators such as negation. So ``2^3x`` is parsed as ``2^(3x)``, and +``2x^3`` is parsed as ``2*(x^3)``. + +Numeric literals also work as coefficients to parenthesized +expressions: + +.. doctest:: + + julia> 2(x-1)^2 - 3(x-1) + 1 + 3 + +Additionally, parenthesized expressions can be used as coefficients to +variables, implying multiplication of the expression by the variable: + +.. doctest:: + + julia> (x-1)x + 6 + +Neither juxtaposition of two parenthesized expressions, nor placing a +variable before a parenthesized expression, however, can be used to +imply multiplication: + +.. doctest:: + + julia> (x-1)(x+1) + ERROR: MethodError: `call` has no method matching call(::Int64, ::Int64) + Closest candidates are: + Union(!Matched::Any...) + BoundsError() + BoundsError(!Matched::Any...) + ... + + julia> x(x+1) + ERROR: MethodError: `call` has no method matching call(::Int64, ::Int64) + Closest candidates are: + Union(!Matched::Any...) + BoundsError() + BoundsError(!Matched::Any...) + ... + +Both expressions are interpreted as function application: any +expression that is not a numeric literal, when immediately followed by a +parenthetical, is interpreted as a function applied to the values in +parentheses (see :ref:`man-functions` for more about functions). +Thus, in both of these cases, an error occurs since the left-hand value +is not a function. + +The above syntactic enhancements significantly reduce the visual noise +incurred when writing common mathematical formulae. Note that no +whitespace may come between a numeric literal coefficient and the +identifier or parenthesized expression which it multiplies. + +Syntax Conflicts +~~~~~~~~~~~~~~~~ + +Juxtaposed literal coefficient syntax may conflict with two numeric literal +syntaxes: hexadecimal integer literals and engineering notation for +floating-point literals. Here are some situations where syntactic +conflicts arise: + +- The hexadecimal integer literal expression ``0xff`` could be + interpreted as the numeric literal ``0`` multiplied by the variable + ``xff``. +- The floating-point literal expression ``1e10`` could be interpreted + as the numeric literal ``1`` multiplied by the variable ``e10``, and + similarly with the equivalent ``E`` form. + +In both cases, we resolve the ambiguity in favor of interpretation as a +numeric literals: + +- Expressions starting with ``0x`` are always hexadecimal literals. +- Expressions starting with a numeric literal followed by ``e`` or + ``E`` are always floating-point literals. + +Literal zero and one +-------------------- + +Julia provides functions which return literal 0 and 1 corresponding to a +specified type or the type of a given variable. + +====================== ===================================================== +Function Description +---------------------- ----------------------------------------------------- +:func:`zero(x) ` Literal zero of type ``x`` or type of variable ``x`` +:func:`one(x) ` Literal one of type ``x`` or type of variable ``x`` +====================== ===================================================== + +These functions are useful in :ref:`man-numeric-comparisons` to avoid overhead +from unnecessary :ref:`type conversion `. + +Examples: + +.. doctest:: + + julia> zero(Float32) + 0.0f0 + + julia> zero(1.0) + 0.0 + + julia> one(Int32) + 1 + + julia> one(BigFloat) + 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 + diff --git a/scripts/Setting.jl b/scripts/Setting.jl index baefd16..1a6096c 100644 --- a/scripts/Setting.jl +++ b/scripts/Setting.jl @@ -19,6 +19,7 @@ juliadoc = DocSet("julia/doc", """ manual/introduction.rst manual/getting-started.rst manual/variables.rst + manual/integers-and-floating-point-numbers.rst """ |> split) phdthesis = DocSet("phdthesis", """ diff --git a/src/julia/doc/manual/integers-and-floating-point-numbers.rst.txt b/src/julia/doc/manual/integers-and-floating-point-numbers.rst.txt new file mode 100644 index 0000000..dd7e3ae --- /dev/null +++ b/src/julia/doc/manual/integers-and-floating-point-numbers.rst.txt @@ -0,0 +1,1073 @@ +== .. _man-integers-and-floating-point-numbers: +== +== .. currentmodule:: Base +== +== ************************************* +++ 정수와 부동소수점으로 표현되는 실수 +-- Integers and Floating-Point Numbers +== ************************************* +== +++ 정수와 부동소수점(floating-point)으로 표현되는 실수는 +++ 수치 연산에 있어서 가장 기본적인 구성 요소이다. +++ 이와 같은 값들의 Julia 내부에서의 내장 표현은 +++ 숫자 프리미티브(numeric primitives)이라고 하고, +++ 실수나 부동소수점처럼 코드상에서 즉각적으로 표현되는 값들은 +++ 수치형 리터럴(numeric literal)이라고 알려져 있다. +++ 예를 들면, ``1``\ 은 정수형 리터럴이지만, +++ ``1.0``\ 은 부동소수점 리터럴이다; +++ 그리고 위 리터럴들이 바이너리 형태로 메모리상에서 표현되는 객체(object)를 +++ 숫자 프리미티브(numeric primitives)라고 한다. +-- Integers and floating-point values are the basic building blocks of +-- arithmetic and computation. Built-in representations of such values are +-- called numeric primitives, while representations of integers and +-- floating-point numbers as immediate values in code are known as numeric +-- literals. For example, ``1`` is an integer literal, while ``1.0`` is a +-- floating-point literal; their binary in-memory representations as +-- objects are numeric primitives. +== +++ Julia는 넓은 범위의 기본 수치 타입과 +++ 수치 연산자, 그리고 비트 연산자를 모두 제공한다. +++ 또한 전 문장에서 언급한 타입과 연산자에 기초한 +++ 표준 수학 함수들도 내장하고 있다. +++ 현대의 컴퓨터에서 기본으로 제공되는 +++ Julia에 내장된 표준 수학 함수들은 +++ Julia로 하여금 연산 자원을 최대한 활용하도록 할 수 있도록 한다. +++ 게다가, Julia는 하드웨어에서 기본적으로 표현하지 못하는 +++ 숫자들을 표현할 수 있게 만든 +++ :ref:`man-arbitrary-precision-arithmetic` 도 지원한다. +++ 그러나, :ref:`man-arbitrary-precision-arithmetic` 를 사용하면 +++ 성능상으로 느려질 수 있다. +-- Julia provides a broad range of primitive numeric types, and a full complement +-- of arithmetic and bitwise operators as well as standard mathematical functions +-- are defined over them. These map directly onto numeric types and operations +-- that are natively supported on modern computers, thus allowing Julia to take +-- full advantage of computational resources. Additionally, Julia provides +-- software support for :ref:`man-arbitrary-precision-arithmetic`, which can +-- handle operations on numeric values that cannot be represented effectively in +-- native hardware representations, but at the cost of relatively slower +-- performance. +== +++ 다음은 Julia에서 기본적으로 지원하는 타입이다: +-- The following are Julia's primitive numeric types: +== +++ - **정수형 타입:** +-- - **Integer types:** +== +++ ================ ======== ========= ============== ================== +-- ================ ======= ============== ============== ================== +++ 타입 부호여부 비트 수 최솟값 최댓값 +-- Type Signed? Number of bits Smallest value Largest value +++ ---------------- -------- --------- -------------- ------------------ +-- ---------------- ------- -------------- -------------- ------------------ +== :class:`Int8` ✓ 8 -2^7 2^7 - 1 +== :class:`UInt8` 8 0 2^8 - 1 +== :class:`Int16` ✓ 16 -2^15 2^15 - 1 +== :class:`UInt16` 16 0 2^16 - 1 +== :class:`Int32` ✓ 32 -2^31 2^31 - 1 +== :class:`UInt32` 32 0 2^32 - 1 +== :class:`Int64` ✓ 64 -2^63 2^63 - 1 +== :class:`UInt64` 64 0 2^64 - 1 +== :class:`Int128` ✓ 128 -2^127 2^127 - 1 +== :class:`UInt128` 128 0 2^128 - 1 +== :class:`Bool` N/A 8 ``false`` (0) ``true`` (1) +++ ================ ======== ========= ============== ================== +-- ================ ======= ============== ============== ================== +== +++ - **부동소수점 타입:** +-- - **Floating-point types:** +== +++ ================ ======= ============== +-- ================ ========= ============== +++ 타입 정밀도 비트수 +-- Type Precision Number of bits +++ ---------------- ------- -------------- +-- ---------------- --------- -------------- +== :class:`Float16` half_ 16 +== :class:`Float32` single_ 32 +== :class:`Float64` double_ 64 +++ ================ ======= ============== +-- ================ ========= ============== +== +== .. _half: https://en.wikipedia.org/wiki/Half-precision_floating-point_format +== .. _single: https://en.wikipedia.org/wiki/Single_precision_floating-point_format +== .. _double: https://en.wikipedia.org/wiki/Double_precision_floating-point_format +== +++ 추가적으로, :ref:`man-complex-and-rational-numbers` 는 위에서 언급한 +++ 타입에 기초하여 만들어졌다. +++ 모든 기본 수치 타입들은 유연하고, 쉽게 확장이 가능한 +++ :ref:`type promotion system ` 덕분에 +++ 명시적인 캐스팅(explicit casting) 없이 자유롭게 상호운용이 가능하다. +-- Additionally, full support for :ref:`man-complex-and-rational-numbers` is built +-- on top of these primitive numeric types. All numeric types interoperate +-- naturally without explicit casting, thanks to a flexible, user-extensible +-- :ref:`type promotion system `. +== +++ 정수 +++ ---- +-- Integers +-- -------- +== +++ 정수 리터럴은 다음과 같은 표준적인 방식으로 표현한다: +-- Literal integers are represented in the standard manner: +== +== .. doctest:: +== +== julia> 1 +== 1 +== +== julia> 1234 +== 1234 +== +++ 정수 리터럴은 해당 시스템이 +++ 32비트 아키텍처인지 혹은 64비트 아키텍처인지에 따라 +++ 타입이 결정된다:: +-- The default type for an integer literal depends on whether the target +-- system has a 32-bit architecture or a 64-bit architecture:: +== +++ +++ # 32비트 시스템: +-- # 32-bit system: +== julia> typeof(1) +== Int32 +== +++ # 64비트 시스템: +-- # 64-bit system: +== julia> typeof(1) +== Int64 +== +++ Julia의 내부 변수 :const:`WORD_SIZE`\ 는 해당 시스템이 +++ 32비트인지 64비트인지 알려주는 역할을 한다.:: +-- The Julia internal variable :const:`WORD_SIZE` indicates whether the target system +-- is 32-bit or 64-bit.:: +== +++ # 32비트 시스템: +-- # 32-bit system: +== julia> WORD_SIZE +== 32 +== +++ # 64비트 시스템: +-- # 64-bit system: +== julia> WORD_SIZE +== 64 +== +++ Julia는 부호가 있는 정수형과 부호가 없는 정수형을 위해 +++ :class:`Int`\ 와 :class:`UInt`\ 라는 타입 또한 정의하고 있다.:: +-- Julia also defines the types :class:`Int` and :class:`UInt`, which are aliases for the +-- system's signed and unsigned native integer types respectively.:: +== +++ .. code-block:: julia +++ +++ # 32비트 시스템: +-- # 32-bit system: +== julia> Int +== Int32 +== julia> UInt +== UInt32 +== +== +++ # 64비트 시스템: +-- # 64-bit system: +== julia> Int +== Int64 +== julia> UInt +== UInt64 +== +++ 32비트로 표현할 수 없지만 64비트로 표현이 가능한 큰 정수형 리터럴은 +++ 시스템의 타입과는 상관없이 항상 64비트를 생성한다.:: +-- Larger integer literals that cannot be represented using only 32 bits +-- but can be represented in 64 bits always create 64-bit integers, +-- regardless of the system type:: +== +++ +++ # 32비트 혹은 64비트 시스템: +-- # 32-bit or 64-bit system: +== julia> typeof(3000000000) +== Int64 +== +++ 부호가 없는 정수형의 입출력은 항상 ``0x``\ 라는 접두어가 붙으며 +++ 16진수는 ``0-9a-f``\ 범위의 숫자와 문자를 쓴다. +++ (입력할 때 대문자 ``A-F``\ 도 쓸 수 있다.) +++ 부호가 없는 값의 크기는 헥사 문자열을 쓴 개수에 따라 결정한다. +-- Unsigned integers are input and output using the ``0x`` prefix and hexadecimal +-- (base 16) digits ``0-9a-f`` (the capitalized digits ``A-F`` also work for input). +-- The size of the unsigned value is determined by the number of hex digits used: +== +== .. doctest:: +== +== julia> 0x1 +== 0x01 +== +== julia> typeof(ans) +== UInt8 +== +== julia> 0x123 +== 0x0123 +== +== julia> typeof(ans) +== UInt16 +== +== julia> 0x1234567 +== 0x01234567 +== +== julia> typeof(ans) +== UInt32 +== +== julia> 0x123456789abcdef +== 0x0123456789abcdef +== +== julia> typeof(ans) +== UInt64 +== +++ 일반적으로 부호가 없는 16진수 정수 리터럴을 쓸 때, +++ 단순히 정수를 표현하기 보다는 +++ 사람들은 고정된 바이트 시퀀스(fixed numeric byte sequence)를 +++ 표현하기 위해 16진수를 쓰는 경향이 있기 때문에, +++ 위와 같이 부호가 없는 정수형에 16진수형태를 결합시키도록 하였다. +-- This behavior is based on the observation that when one uses unsigned +-- hex literals for integer values, one typically is using them to +-- represent a fixed numeric byte sequence, rather than just an integer +-- value. +== +++ :data:`ans`\ 가 대화형 실행 환경에서 가장 최근에 실행된 표현식의 결과를 +++ 나타내었다는 것을 떠올려보면, 위의 Julia 코드는 다른 환경에서는 +++ 제대로 실행이 안될 것이라는 것을 알 수 있다. +-- Recall that the variable :data:`ans` is set to the value of the last expression +-- evaluated in an interactive session. This does not occur when Julia code is +-- run in other ways. +== +++ Julia는 2진수와 8진수 리터럴 또한 지원한다: +-- Binary and octal literals are also supported: +== +== .. doctest:: +== +== julia> 0b10 +== 0x02 +== +== julia> typeof(ans) +== UInt8 +== +== julia> 0o10 +== 0x08 +== +== julia> typeof(ans) +== UInt8 +== +++ 정수형과 같은 기본 수치 타입의 최소값과 최대값은 +++ :func:`typemin`\ 과 :func:`typemax`\ 함수를 통해 알 수 있다. +-- The minimum and maximum representable values of primitive numeric types +-- such as integers are given by the :func:`typemin` and :func:`typemax` functions: +== +== .. doctest:: +== +== julia> (typemin(Int32), typemax(Int32)) +== (-2147483648,2147483647) +== +== julia> for T in [Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128] +== println("$(lpad(T,7)): [$(typemin(T)),$(typemax(T))]") +== end +== Int8: [-128,127] +== Int16: [-32768,32767] +== Int32: [-2147483648,2147483647] +== Int64: [-9223372036854775808,9223372036854775807] +== Int128: [-170141183460469231731687303715884105728,170141183460469231731687303715884105727] +== UInt8: [0,255] +== UInt16: [0,65535] +== UInt32: [0,4294967295] +== UInt64: [0,18446744073709551615] +== UInt128: [0,340282366920938463463374607431768211455] +== +++ :func:`typemin`\ 과 :func:`typemax`\ 가 제공하는 값들은 +++ 항상 매개변수의 타입과 같은 타입을 가진다. +++ (위 예제에서 쓰는 :ref:`for loops `\ , +++ :ref:`man-strings`\ , :ref:`man-string-interpolation`\ , +++ 과 같은 표현들은 아직 소개하지 않은 것들이다. +++ 그러나 약간의 프로그래밍 지식이 있다면 이해하기에 별 문제가 없을 것이다.) +-- The values returned by :func:`typemin` and :func:`typemax` are always of the +-- given argument type. (The above expression uses several features we have +-- yet to introduce, including :ref:`for loops `, +-- :ref:`man-strings`, and :ref:`man-string-interpolation`, +-- but should be easy enough to understand for users with some existing +-- programming experience.) +== +== +++ 오버플로우(Overflow) 동작 +++ ~~~~~~~~~~~~~~~~~~~~~~~~~ +-- Overflow behavior +-- ~~~~~~~~~~~~~~~~~ +== +++ Julia에서는 주어진 타입에서 표현할 수 있는 값을 넘어서게 되면 +++ 다음과 같이 주어진 범위를 벗어나지 않는(wraparound) 동작을 보여준다. +-- In Julia, exceeding the maximum representable value of a given type results in +-- a wraparound behavior: +== +== .. doctest:: +== +== julia> x = typemax(Int64) +== 9223372036854775807 +== +== julia> x + 1 +== -9223372036854775808 +== +== julia> x + 1 == typemin(Int64) +== true +== +++ 위와 같기 때문에, Julia 정수의 연산은 사실 +++ `나머지 연산 `_\ 임을 +++ 알 수 있다. +++ 오버플로우가 나올 수 있는 프로그램에서는, +++ 오버플로우를 명시적으로 체크하는 것이 필수적이다; +++ 그런 경우가 아니라면 +++ :ref:`man-arbitrary-precision-arithmetic`\ 에서 ``BigInt``\ 타입을 +++ 사용하는 것을 추천한다. +-- Thus, arithmetic with Julia integers is actually a form of `modular arithmetic +-- `_. This reflects the +-- characteristics of the underlying arithmetic of integers as implemented on +-- modern computers. In applications where overflow is possible, explicit checking +-- for wraparound produced by overflow is essential; otherwise, the ``BigInt`` type +-- in :ref:`man-arbitrary-precision-arithmetic` is recommended instead. +== +++ 나눗셈 관련 에러들 +++ ~~~~~~~~~~~~~~~~~~ +-- Division errors +-- ~~~~~~~~~~~~~~~ +== +++ 정수의 나눗셈 연산 (``div`` 함수)는 두 가지 예외적인 경우가 있다; +++ 0으로 나누기, 그리고 컴퓨터가 표현할 수 있는 최소의 음의 정수값을 +++ -1로 나누는 것이다. +++ 두 가지 경우 모두 :exc:`DivideError`\ 를 유발한다. +++ 두 `나머지` 연산 함수(remainder 와 modulus, ``rem``\ 와 ``mod``\ )는 +++ 두번째 매개변수가 0일 때 :exc:`DivideError`\ 를 던진다(throw). +-- Integer division (the ``div`` function) has two exceptional cases: dividing by +-- zero, and dividing the lowest negative number (:func:`typemin`) by -1. Both of +-- these cases throw a :exc:`DivideError`. The remainder and modulus functions +-- (``rem`` and ``mod``) throw a :exc:`DivideError` when their second argument is +-- zero. +== +++ 부동소수점으로 표현되는 실수 +++ ---------------------------- +-- Floating-Point Numbers +-- ---------------------- +== +++ 부동소수점 리터럴은 표준 포맷을 이용하여 표현된다.: +-- Literal floating-point numbers are represented in the standard formats: +== +== .. doctest:: +== +== julia> 1.0 +== 1.0 +== +== julia> 1. +== 1.0 +== +== julia> 0.5 +== 0.5 +== +== julia> .5 +== 0.5 +== +== julia> -1.23 +== -1.23 +== +== julia> 1e10 +== 1.0e10 +== +== julia> 2.5e-4 +== 0.00025 +== +++ 위에 나온 결과는 모두 ``Float64`` 타입의 값들이다. +++ ``Float32`` 값들은 ``e`` 대신에 ``f``\ 를 쓰면 입력할 수 있다. +-- The above results are all ``Float64`` values. Literal ``Float32`` values can +-- be entered by writing an ``f`` in place of ``e``: +== +== .. doctest:: +== +== julia> 0.5f0 +== 0.5f0 +== +== julia> typeof(ans) +== Float32 +== +== julia> 2.5f-4 +== 0.00025f0 +== +++ 값들은 쉽게 ``Float32`` 타입으로 변환할 수 있다. +-- Values can be converted to ``Float32`` easily: +== +== .. doctest:: +== +== julia> Float32(-1.5) +== -1.5f0 +== +== julia> typeof(ans) +== Float32 +== +++ 16진수로 표현되는 부동소수점 리터럴은 유효하지만, +++ ``Float64`` 타입에서만 가능하다. +-- Hexadecimal floating-point literals are also valid, but only as ``Float64`` values: +== +== .. doctest:: +== +== julia> 0x1p0 +== 1.0 +== +== julia> 0x1.8p3 +== 12.0 +== +== julia> 0x.4p-1 +== 0.125 +== +== julia> typeof(ans) +== Float64 +== +++ 16비트의 정밀도를 가지는 반정도 부동소수점도 지원된다. (``Float16``\ ) +++ 하지만 메모리에 저장할 때만 쓰이고 계산할 때는 자동으로 +++ ``Float32``\ 로 변환된다. +-- Half-precision floating-point numbers are also supported (``Float16``), but +-- only as a storage format. In calculations they'll be converted to ``Float32``: +== +== .. doctest:: +== +== julia> sizeof(Float16(4.)) +== 2 +== +== julia> 2*Float16(4.) +== 8.0f0 +== +++ 밑줄 ``_``\ 는 수 구분자로 쓰일 수 있다. +-- The underscore ``_`` can be used as digit separator: +== +== .. doctest:: +== +== julia> 10_000, 0.000_000_005, 0xdead_beef, 0b1011_0010 +== (10000,5.0e-9,0xdeadbeef,0xb2) +== +++ 실수로서의 숫자 0 +++ ~~~~~~~~~~~~~~~~~~ +-- Floating-point zero +-- ~~~~~~~~~~~~~~~~~~~ +== +++ 부동소수점은 양수 0과 음수 0으로 불리우는 +++ `두 개의 0 `_\ 을 +++ 가진다. 그 둘은 값은 0으로써 같지만, +++ 다음과 같이 ``bits`` 함수를 이용하면 알 수 있듯이, +++ 바이너리로 표기했을 때 다르다는 것을 알 수 있다. +-- Floating-point numbers have `two zeros +-- `_, positive zero and negative zero. +-- They are equal to each other but have different binary representations, as can +-- be seen using the ``bits`` function: : +== +== .. doctest:: +== +== julia> 0.0 == -0.0 +== true +== +== julia> bits(0.0) +== "0000000000000000000000000000000000000000000000000000000000000000" +== +== julia> bits(-0.0) +== "1000000000000000000000000000000000000000000000000000000000000000" +== +== .. _man-special-floats: +== +++ 특별한 부동소수점 값들 +++ ~~~~~~~~~~~~~~~~~~~~~~~ +-- Special floating-point values +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +== +++ 다음은 실수에는 포함되지는 않은 +++ 세 종류의 특정 표준 부동소수점이 있다. +-- There are three specified standard floating-point values that do not +-- correspond to any point on the real number line: +== +== =========== =========== =========== ================= ================================================================= +++ 특별한 값 이름 설명 +-- Special value Name Description +== ----------------------------------- ----------------- ----------------------------------------------------------------- +== ``Float16`` ``Float32`` ``Float64`` +== =========== =========== =========== ================= ================================================================= +++ ``Inf16`` ``Inf32`` ``Inf`` positive infinity 모든 유한한 부동소수점 실수보다 큰 값 +++ ``-Inf16`` ``-Inf32`` ``-Inf`` negative infinity 모든 유한한 부동소수점 실수보다 작은 값 +++ ``NaN16`` ``NaN32`` ``NaN`` not a number 어떠한 부동소수점 실수와도 같지 않은 값 (자기 자신 포함) +-- ``Inf16`` ``Inf32`` ``Inf`` positive infinity a value greater than all finite floating-point values +-- ``-Inf16`` ``-Inf32`` ``-Inf`` negative infinity a value less than all finite floating-point values +-- ``NaN16`` ``NaN32`` ``NaN`` not a number a value not ``==`` to any floating-point value (including itself) +== =========== =========== =========== ================= ================================================================= +== +++ 이와 같은 유한하지 않은 부동소수점 값들이 +++ 서로와 다른 실수에 대해서 순서를 매길 때에는, +++ :ref:`man-numeric-comparisons`\ 를 참고하길 바란다. +++ `IEEE 754 standard `_\ 에 따르면, +++ 위에서의 부동소수점 실수들은 어떤 산술 연산에 의한 결과임을 알 수 있다. +-- For further discussion of how these non-finite floating-point values are +-- ordered with respect to each other and other floats, see +-- :ref:`man-numeric-comparisons`. By the +-- `IEEE 754 standard `_, these +-- floating-point values are the results of certain arithmetic operations: +== +== .. doctest:: +== +== julia> 1/Inf +== 0.0 +== +== julia> 1/0 +== Inf +== +== julia> -5/0 +== -Inf +== +== julia> 0.000001/0 +== Inf +== +== julia> 0/0 +== NaN +== +== julia> 500 + Inf +== Inf +== +== julia> 500 - Inf +== -Inf +== +== julia> Inf + Inf +== Inf +== +== julia> Inf - Inf +== NaN +== +== julia> Inf * Inf +== Inf +== +== julia> Inf / Inf +== NaN +== +== julia> 0 * Inf +== NaN +== +++ :func:`typemin`\ 과 :func:`typemax` 함수는 +++ 부동소수점 타입에도 적용이 가능하다. +-- The :func:`typemin` and :func:`typemax` functions also apply to floating-point +-- types: +== +== .. doctest:: +== +== julia> (typemin(Float16),typemax(Float16)) +== (-Inf16,Inf16) +== +== julia> (typemin(Float32),typemax(Float32)) +== (-Inf32,Inf32) +== +== julia> (typemin(Float64),typemax(Float64)) +== (-Inf,Inf) +== +== +++ 계산기 입실론(Machine epsilon) +++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +-- Machine epsilon +-- ~~~~~~~~~~~~~~~ +== +++ 대부분의 실수들은 부동소수점 형태로는 정확하게 표현할 수 없다. +++ 그리고 현재로서는 많은 경우 두 인접한 부동소수점으로 표현 가능한 실수가 +++ 얼만큼 떨어져 있는 지 알 필요가 있다. +++ 따라서 이를 위해 계산기 입실론(machine epsilon)이라는 개념이 도입하게 되었다. +-- Most real numbers cannot be represented exactly with floating-point numbers, +-- and so for many purposes it is important to know the distance between two +-- adjacent representable floating-point numbers, which is often known as +-- `machine epsilon `_. +== +++ Julia는 :func:`eps`\ 라는 것을 제공한다. +++ 이는 표현 가능한 부동소수점 실수 중에서 ``1.0`` 과 +++ ``1.0``\ 보다 크면서 ``1.0``\ 의 옆에 있는 값과의 거리를 말한다. +-- Julia provides :func:`eps`, which gives the distance between ``1.0`` +-- and the next larger representable floating-point value: +== +== .. doctest:: +== +== julia> eps(Float32) +== 1.1920929f-7 +== +== julia> eps(Float64) +== 2.220446049250313e-16 +== +== julia> eps() # same as eps(Float64) +== 2.220446049250313e-16 +== +++ 위 코드에서 나오는 ``eps`` 값들은 +++ ``Float32``\ 와 ``Float64`` 값 중에서 바이너리로 표기했을 때 +++ ``2.0^-23`` 과 ``2.0^-52``\ 를 각각 나타낸다. +++ :func:`eps` 함수는 부동소수점 실수를 매개변수로 받을 수도 있는데, +++ 이 때는 ``1.0``\ 이 아니라 주어진 값과 주어진 값 바로 옆에서 +++ 주어진 값과의 거리를 반환한다. +++ 그 말은 ``eps(x)``\ 의 반환값은 ``x``\ 와 같은 타입이고, +++ ``x + eps(x)``\ 는 ``x``\ 보다 큰 ``x`` 바로 옆에 있는 +++ 표현 가능한 부동소수점 실수를 뜻한다. +-- These values are ``2.0^-23`` and ``2.0^-52`` as ``Float32`` and ``Float64`` +-- values, respectively. The :func:`eps` function can also take a +-- floating-point value as an argument, and gives the absolute difference +-- between that value and the next representable floating point value. That +-- is, ``eps(x)`` yields a value of the same type as ``x`` such that +-- ``x + eps(x)`` is the next representable floating-point value larger +-- than ``x``: +== +== .. doctest:: +== +== julia> eps(1.0) +== 2.220446049250313e-16 +== +== julia> eps(1000.) +== 1.1368683772161603e-13 +== +== julia> eps(1e-27) +== 1.793662034335766e-43 +== +== julia> eps(0.0) +== 5.0e-324 +== +++ 두 인접하면서 표현 가능한 부동소수점 실수들은 상수가 아니지만, +++ 작은 값에서는 작은 값을 지니고, 큰 값들에서는 큰 값을 나타낸다. +++ 다른 말로 말하면, 표현 가능한 부동소수점 실수들은 실수축 상에서 +++ 0에 근접할 때 가장 밀집되어있고, 0에서 멀어질수록 점점 드물다. +++ 정의에 의하면, ``eps(1.0)``\ 은 ``eps(Float64)``\ 와 같은데, 그 이유는 +++ ``1.0``\ 은 64비트 부동소수점 실수이기 때문이다. +-- The distance between two adjacent representable floating-point numbers is not +-- constant, but is smaller for smaller values and larger for larger values. In +-- other words, the representable floating-point numbers are densest in the real +-- number line near zero, and grow sparser exponentially as one moves farther away +-- from zero. By definition, ``eps(1.0)`` is the same as ``eps(Float64)`` since +-- ``1.0`` is a 64-bit floating-point value. +== +++ 또한 Julia는 :func:`nextfloat`\ 과 :func:`prevfloat` 함수를 제공하는데 이는, +++ 표현 가능한 부동소수점 실수 중에서 주어진 실수 바로 옆에 있는 +++ 크거나 작은 수를 반환한다. +-- Julia also provides the :func:`nextfloat` and :func:`prevfloat` functions which return +-- the next largest or smallest representable floating-point number to the +-- argument respectively: : +== +== .. doctest:: +== +== julia> x = 1.25f0 +== 1.25f0 +== +== julia> nextfloat(x) +== 1.2500001f0 +== +== julia> prevfloat(x) +== 1.2499999f0 +== +== julia> bits(prevfloat(x)) +== "00111111100111111111111111111111" +== +== julia> bits(x) +== "00111111101000000000000000000000" +== +== julia> bits(nextfloat(x)) +== "00111111101000000000000000000001" +== +++ 위의 예제는 서로 이웃한 표현 가능한 부동소수점 수는 +++ 바이너리 정수 표기법을 가질 수 있다는 기본적인 원리를 새삼 일깨워 준다. +-- This example highlights the general principle that the adjacent representable +-- floating-point numbers also have adjacent binary integer representations. +== +++ 반올림 모드 +++ ~~~~~~~~~~~ +-- Rounding modes +-- ~~~~~~~~~~~~~~ +== +++ 만약 어떤 숫자가 정확한 부동소수점 표현을 가지고 있지 않다면, +++ 그 수는 반드시 어떤 표현 가능한 값으로 반올림되어야 한다. +++ 그러나, 만약 사용자가 원한다면, +++ `IEEE 754 standard `_\ 에 +++ 따라 반올림 방식에 대해서는 변경할 수 있다.:: +-- If a number doesn't have an exact floating-point representation, it must be +-- rounded to an appropriate representable value, however, if wanted, the manner +-- in which this rounding is done can be changed according to the rounding modes +-- presented in the `IEEE 754 standard `_:: +== +== +== julia> 1.1 + 0.1 +== 1.2000000000000002 +== +== julia> with_rounding(Float64,RoundDown) do +== 1.1 + 0.1 +== end +== 1.2 +== +++ 기본 반올림 모드는 항상 :const:`RoundNearest`\ 이다. +++ 이는 가장 근접한 표현 가능한 값으로 반올림하되, +++ 만약 두 표현 가능한 값 중간에 주어진 값이 걸쳐 있으면 +++ 가수부 값중 짝수(바이너리이므로 0)로 반올림 하는 모드이다. +-- The default mode used is always :const:`RoundNearest`, which rounds to the nearest +-- representable value, with ties rounded towards the nearest value with an even +-- least significant bit. +== +++ .. warning:: 반올림은 일반적으로 기본 산술 함수 +++ (:func:`+`, :func:`-`, :func:`*`, :func:`/` and :func:`sqrt`)와 +++ 타입 변환 연산에서만 정확하다. 많은 다른 함수들은 +++ 기본 값인 :const:`RoundNearest`\ 를 가정하고 짜여져 있고, +++ 이는 다른 반올림 모드에서는 부정확한 값을 제공할 수 있다. +-- .. warning:: Rounding is generally only correct for basic arithmetic functions +-- (:func:`+`, :func:`-`, :func:`*`, :func:`/` and :func:`sqrt`) and +-- type conversion operations. Many other functions assume the +-- default :const:`RoundNearest` mode is set, and can give erroneous +-- results when operating under other rounding modes. +== +++ 부동소수점 실수에 대해서 더 읽으면 좋은 문서들 +++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +-- Background and References +-- ~~~~~~~~~~~~~~~~~~~~~~~~~ +== +++ 부동소수점 연산은 많은 미묘한 것들을 수반하고 있기 때문에 +++ 저수준(low-level) 구현에 익숙하지 않은 유저들은 당황할 수도 있다. +++ 그러나 그 미묘한 점들은 과학적 연산과 관련된 많은 책들에서 잘 설명되고 있고, +++ 아래에 나열하는 참고문헌도 참고하면 좋을 것이다: +-- Floating-point arithmetic entails many subtleties which can be surprising to +-- users who are unfamiliar with the low-level implementation details. However, +-- these subtleties are described in detail in most books on scientific +-- computation, and also in the following references: +== +++ - 부동소수점과 관련해서 가장 확실한 가이드는 `IEEE 754-2008 +++ Standard `_\ +++ 이지만, 유료이다. +-- - The definitive guide to floating point arithmetic is the `IEEE 754-2008 +-- Standard `_; +-- however, it is not available for free online. +++ - 부동소수점이 어떻게 표현되는지에 대한 간략하면서도 명쾌한 설명은 +++ John D. Cook의 `블로그 글 +++ `_ +++ 을 참고하면 된다. 같은 주제에 관하여 이와 더불어서 그의 +++ `소개글 +++ `_\ +++ 글은 부동소수점이 실수의 이상적인 추상화와 다름으로써 생기는 +++ 몇 가지 문제에 대해서도 다루고 있다. +-- - For a brief but lucid presentation of how floating-point numbers are +-- represented, see John D. Cook's `article +-- `_ +-- on the subject as well as his `introduction +-- `_ +-- to some of the issues arising from how this representation differs in +-- behavior from the idealized abstraction of real numbers. +++ - Bruce Dawson의 `series of blog posts on floating-point +++ numbers `_ 도 +++ 추천하는 바이다. +-- - Also recommended is Bruce Dawson's `series of blog posts on floating-point +-- numbers `_. +++ - 상급자들은 부동소수점의 내부 구현에 관한 이야기들과 +++ 부동소수점 연산을 할 때 맞닥뜨릴 수 있는 수치적인 정확도에 관한 문제들에 +++ 대해서는 David Goldberg의 논문, `What Every Computer Scientist Should Know About Floating-Point +++ Arithmetic +++ `_ 을 +++ 참고하는 것이 좋다. +-- - For an excellent, in-depth discussion of floating-point numbers and issues of +-- numerical accuracy encountered when computing with them, see David Goldberg's +-- paper `What Every Computer Scientist Should Know About Floating-Point +-- Arithmetic +-- `_. +++ - 부동소수점에 관한 역사, 근원, 몇 가지 이슈들 뿐만 아니라 수치 해석과 관련한 +++ 많은 다양한 이야기들에 대한 자세한 문서를 얻고 싶다면 +++ `William Kahan `_\ 가 작성한 +++ `collected writings +++ `_\ 을 참고하는 것을 추천한다. +++ 이 문서는 "부동소수점의 아버지(Father of Floating-Point)"라고도 알려져 있다. +++ - 특별히 부동소수점의 역사에 관해서 관심이 더 생긴다면, +++ `An Interview with the Old +++ Man of Floating-Point +++ `_\ 을 +++ 읽기를 바란다. +-- - For even more extensive documentation of the history of, rationale for, +-- and issues with floating-point numbers, as well as discussion of many other +-- topics in numerical computing, see the `collected writings +-- `_ of `William Kahan +-- `_, commonly known as the "Father +-- of Floating-Point". Of particular interest may be `An Interview with the Old +-- Man of Floating-Point +-- `_. +== +== .. _man-arbitrary-precision-arithmetic: +== +++ 임의 정밀도 연산 +++ ---------------- +-- Arbitrary Precision Arithmetic +-- ------------------------------ +== +++ 임의 정밀도의 정수와 부동소수점들의 연산을 위해, Julia는 +++ `GNU Multiple Precision Arithmetic Library (GMP) `_\ 와 +++ `GNU MPFR Library `_\ 을 각각 래핑(wrapping)하였다. +++ :class:`BigInt`\ 와 :class:`BigFloat` 타입은 Julia에서 +++ 각각 임의 정밀도의 정수와 부동소수점을 다루기 위해 사용되고 있다. +-- To allow computations with arbitrary-precision integers and floating point numbers, +-- Julia wraps the `GNU Multiple Precision Arithmetic Library (GMP) `_ and the `GNU MPFR Library `_, respectively. +-- The :class:`BigInt` and :class:`BigFloat` types are available in Julia for arbitrary precision +-- integer and floating point numbers respectively. +== +++ 기본 수치 타입으로부터 임의 정밀도 정수와 부동소수점 타입을 만들기 위해 +++ 생성자가 존재하며, :func:`parse`\ 는 :class:`AbstractString`\ 들로부터 +++ 임의 정밀도 타입을 만들 수 있게 해준다. +++ 한번 임의 정밀도 타입이 만들어지면, +++ :ref:`type promotion and conversion mechanism ` +++ 덕분에 자유롭게 다른 수치타입과 연산을 수행할 수 있다. +-- Constructors exist to create these types from primitive numerical types, and +-- :func:`parse` can be use to construct them from :class:`AbstractString`\ s. Once +-- created, they participate in arithmetic with all other numeric types thanks to +-- Julia's +-- :ref:`type promotion and conversion mechanism `: +== +== .. doctest:: +== +== julia> BigInt(typemax(Int64)) + 1 +== 9223372036854775808 +== +== julia> parse(BigInt, "123456789012345678901234567890") + 1 +== 123456789012345678901234567891 +== +== julia> parse(BigFloat, "1.23456789012345678901") +== 1.234567890123456789010000000000000000000000000000000000000000000000000000000004 +== +== julia> BigFloat(2.0^66) / 3 +== 2.459565876494606882133333333333333333333333333333333333333333333333333333333344e+19 +== +== julia> factorial(BigInt(40)) +== 815915283247897734345611269596115894272000000000 +== +++ 그러나, 기본 타입과 :class:`BigInt`/:class:`BigFloat` 간의 +++ 묵시적 형 변환(type promotion)은 자동으로 이루어지지 않고, +++ 반드시 명시적으로 처리되어야 한다. +-- However, type promotion between the primitive types above and +-- :class:`BigInt`/:class:`BigFloat` is not automatic and must be explicitly stated. +== +== .. doctest:: +== +== julia> x = typemin(Int64) +== -9223372036854775808 +== +== julia> x = x - 1 +== 9223372036854775807 +== +== julia> typeof(x) +== Int64 +== +== julia> y = BigInt(typemin(Int64)) +== -9223372036854775808 +== +== julia> y = y - 1 +== -9223372036854775809 +== +== julia> typeof(y) +== Base.GMP.BigInt +== +++ :class:`BigFloat` 타입에서 기본 정밀도(가수부의 비트수)와 반올림 모드는 +++ :func:`set_bigfloat_precision`\ 와 :func:`set_rounding`\ 를 호출함으로써 +++ 변경할 수 있으며, 한 번 호출된 이후에는 그 설정이 계속 유지된다. +++ 특정 블럭의 코드에서만 정밀도와 반올림을 변경하기 위해서는 +++ :func:`with_bigfloat_precision`\ 와 :func:`with_rounding`\ 를 호출한다: +-- The default precision (in number of bits of the significand) and +-- rounding mode of :class:`BigFloat` operations can be changed globally +-- by calling :func:`set_bigfloat_precision` and +-- :func:`set_rounding`, and all further calculations will take +-- these changes in account. Alternatively, the precision or the +-- rounding can be changed only within the execution of a particular +-- block of code by :func:`with_bigfloat_precision` or +-- :func:`with_rounding`: +== +== .. doctest:: +== +== julia> with_rounding(BigFloat,RoundUp) do +== BigFloat(1) + parse(BigFloat, "0.1") +== end +== 1.100000000000000000000000000000000000000000000000000000000000000000000000000003 +== +== julia> with_rounding(BigFloat,RoundDown) do +== BigFloat(1) + parse(BigFloat, "0.1") +== end +== 1.099999999999999999999999999999999999999999999999999999999999999999999999999986 +== +== julia> with_bigfloat_precision(40) do +== BigFloat(1) + parse(BigFloat, "0.1") +== end +== 1.1000000000004 +== +== +== .. _man-numeric-literal-coefficients: +== +++ 수치형 리터럴 계수 +++ ---------------------------- +-- Numeric Literal Coefficients +-- ---------------------------- +== +++ 보통의 수학 식과 표현식을 깔끔하게 표현하기 위해서, +++ Julia는 변수가 수치형 리터럴 바로 다음에 있으면, +++ 둘 사이의 관계가 곱셈임을 가정한다. +++ 이는 다항식의 표현을 더욱 깔끔하게 만든다: +-- To make common numeric formulas and expressions clearer, Julia allows +-- variables to be immediately preceded by a numeric literal, implying +-- multiplication. This makes writing polynomial expressions much cleaner: +== +== .. doctest:: +== +== julia> x = 3 +== 3 +== +== julia> 2x^2 - 3x + 1 +== 10 +== +== julia> 1.5x^2 - .5x + 1 +== 13.0 +== +++ 이는 지수함수의 포현도 매우 아름답게 만들 수 있다: +-- It also makes writing exponential functions more elegant: +== +== .. doctest:: +== +== julia> 2^2x +== 64 +== +++ 수치형 리터럴 계수의 선행(precedence)도 +++ 부정연산과 같은 단항 연산과 같이 작동한다. +++ 따라서 ``2^3x``\ 는 ``2^(3x)``\ 로, +++ ``2x^3``\ 은 ``2*(x^3)``\ 으로 파싱(parsing)된다. +-- The precedence of numeric literal coefficients is the same as that of unary +-- operators such as negation. So ``2^3x`` is parsed as ``2^(3x)``, and +-- ``2x^3`` is parsed as ``2*(x^3)``. +== +++ 수치형 리터럴은 괄호가 있는 식에서도 계수(coefficients)로 작동할 수 있다. +-- Numeric literals also work as coefficients to parenthesized +-- expressions: +== +== .. doctest:: +== +== julia> 2(x-1)^2 - 3(x-1) + 1 +== 3 +== +++ 게다가 괄호 표현식은 변수 또한 계수로 생각하여, +++ 곱셈기호 없이도 변수들 간의 곱으로 식을 표현할 수도 있다. +-- Additionally, parenthesized expressions can be used as coefficients to +-- variables, implying multiplication of the expression by the variable: +== +== .. doctest:: +== +== julia> (x-1)x +== 6 +== +++ 그러나 두 괄호식을 병치하거나 괄호식 앞에 변수를 두는 경우는 +++ 계수로 사용할 수 없다. +-- Neither juxtaposition of two parenthesized expressions, nor placing a +-- variable before a parenthesized expression, however, can be used to +-- imply multiplication: +== +== .. doctest:: +== +== julia> (x-1)(x+1) +== ERROR: MethodError: `call` has no method matching call(::Int64, ::Int64) +== Closest candidates are: +== Union(!Matched::Any...) +== BoundsError() +== BoundsError(!Matched::Any...) +== ... +== +== julia> x(x+1) +== ERROR: MethodError: `call` has no method matching call(::Int64, ::Int64) +== Closest candidates are: +== Union(!Matched::Any...) +== BoundsError() +== BoundsError(!Matched::Any...) +== ... +== +++ 두 표현식은 함수로써 인식된다: 괄호앞에 붙는 수치형 리터럴이 아닌 +++ 표현식들은 모두 함수와 함수의 매개변수로 인식된다. +++ (자세한 설명을 위해서는 :ref:`man-functions`\ 를 참고하도록 하자) +++ 그래서 두 가지 경우 모두 왼쪽에 있는 값이 +++ 함수가 아님을 알려주는 에러가 발생한다. +-- Both expressions are interpreted as function application: any +-- expression that is not a numeric literal, when immediately followed by a +-- parenthetical, is interpreted as a function applied to the values in +-- parentheses (see :ref:`man-functions` for more about functions). +-- Thus, in both of these cases, an error occurs since the left-hand value +-- is not a function. +== +++ 위에서 언급한 문법적 강화효과는 수학식을 작성할 때 생기는 시각적 공해를 +++ 줄일 수 있도록 해준다. 단지 한 가지 알아야 할 점은 +++ 수치형 계수와 이에 곱해지는 변수 혹은 괄호식등 사이에는 +++ 빈칸이 있어서는 안된다. +-- The above syntactic enhancements significantly reduce the visual noise +-- incurred when writing common mathematical formulae. Note that no +-- whitespace may come between a numeric literal coefficient and the +-- identifier or parenthesized expression which it multiplies. +== +++ 문법적 충돌 +++ ~~~~~~~~~~~ +-- Syntax Conflicts +-- ~~~~~~~~~~~~~~~~ +== +++ 리터럴 계수를 병치하는 문법은 +++ 16진수 정수 리터럴과 부동소수점의 공학적 표현라는 +++ 두 수치형 리터럴 문법과 충돌이 생길 수 있다 +++ 다음은 문법적 충돌이 발생하는 예이다. +-- Juxtaposed literal coefficient syntax may conflict with two numeric literal +-- syntaxes: hexadecimal integer literals and engineering notation for +-- floating-point literals. Here are some situations where syntactic +-- conflicts arise: +== +++ 16진수 리터럴 표현식 ``0xff``\ 는 수치형 리터럴 ``0``\ 과 변수 ``xff``\ 의 +++ 곱셈으로 해석될 수 있다. +-- - The hexadecimal integer literal expression ``0xff`` could be +-- interpreted as the numeric literal ``0`` multiplied by the variable +-- ``xff``. +++ 부동소수점 리터럴 표현식 ``1e10``\ 은 수치형 리터럴 ``1``\ 이 +++ 변수 ``e10``\ 에 곱해지는 걸로 해석될 수 있고 이는 ``e``\ 가 아닌, +++ ``E``\ 를 쓸 때에도 마찬가지이다. +-- - The floating-point literal expression ``1e10`` could be interpreted +-- as the numeric literal ``1`` multiplied by the variable ``e10``, and +-- similarly with the equivalent ``E`` form. +== +++ 이 두 가지 경우에, 우리는 수치형 리터럴을 해석하는데 있어서 +++ 다음과 같은 방식으로 모호함을 해결했다. +-- In both cases, we resolve the ambiguity in favor of interpretation as a +-- numeric literals: +== +++ - ``0x``\ 로 시작하는 표현식은 항상 16진수 리터럴이다. +++ - 수치형 리터럴으로 시작하는 표현식에서 수치형 리터럴 다음에 ``e`` 혹은 +++ ``E``\ 가 뒤따라오면 항상 부동소수점 리터럴이다. +-- - Expressions starting with ``0x`` are always hexadecimal literals. +-- - Expressions starting with a numeric literal followed by ``e`` or +-- ``E`` are always floating-point literals. +== +++ 리터럴 0와 1 +++ ------------ +-- Literal zero and one +-- -------------------- +== +++ Julia는 어떤 특정한 타입이나 주어진 변수의 타입에 따라 리터럴 0이나 1을 +++ 리턴하는 함수를 제공한다. +-- Julia provides functions which return literal 0 and 1 corresponding to a +-- specified type or the type of a given variable. +== +== ====================== ===================================================== +++ 함수 설명 +-- Function Description +== ---------------------- ----------------------------------------------------- +++ :func:`zero(x) ` ``x`` 타입이나 변수 ``x``\ 의 타입의 리터럴 0 +++ :func:`one(x) ` ``x`` 타입이나 변수 ``x``\ 의 타입의 리터럴 1 +-- :func:`zero(x) ` Literal zero of type ``x`` or type of variable ``x`` +-- :func:`one(x) ` Literal one of type ``x`` or type of variable ``x`` +== ====================== ===================================================== +== +++ 위 함수들은 :ref:`man-numeric-comparisons`\ 에서 +++ 불필요한 :ref:`type conversion `\ 에 +++ 의한 성능저하를 줄일 때 유용하다. +-- These functions are useful in :ref:`man-numeric-comparisons` to avoid overhead +-- from unnecessary :ref:`type conversion `. +== +++ 예제: +-- Examples: +== +== .. doctest:: +== +== julia> zero(Float32) +== 0.0f0 +== +== julia> zero(1.0) +== 0.0 +== +== julia> one(Int32) +== 1 +== +== julia> one(BigFloat) +== 1.000000000000000000000000000000000000000000000000000000000000000000000000000000 +==