├── .codecov.yml ├── REQUIRE ├── docs ├── src │ ├── assets │ │ ├── julia-manual.css │ │ └── logo.png │ ├── base │ │ ├── libc.md │ │ ├── stacktraces.md │ │ ├── iterators.md │ │ ├── constants.md │ │ ├── parallel.md │ │ ├── c.md │ │ ├── multi-threading.md │ │ ├── simd-types.md │ │ ├── file.md │ │ ├── strings.md │ │ ├── numbers.md │ │ ├── math.md │ │ ├── arrays.md │ │ ├── io-network.md │ │ ├── punctuation.md │ │ ├── sort.md │ │ ├── collections.md │ │ └── base.md │ ├── juliacn │ │ └── style-guide.md │ ├── manual │ │ ├── variables.md │ │ ├── getting-started.md │ │ ├── complex-and-rational-numbers.md │ │ ├── mathematical-operations.md │ │ ├── style-guide.md │ │ └── integers-and-floating-point-numbers.md │ └── index.md ├── README.md └── make.jl ├── src ├── JuliaZH.jl └── basedocs.jl ├── test └── runtests.jl ├── .gitignore ├── LICENSE.md ├── .travis.yml ├── README.md └── appveyor.yml /.codecov.yml: -------------------------------------------------------------------------------- 1 | comment: false 2 | -------------------------------------------------------------------------------- /REQUIRE: -------------------------------------------------------------------------------- 1 | julia 0.7 2 | Compat 3 | -------------------------------------------------------------------------------- /docs/src/assets/julia-manual.css: -------------------------------------------------------------------------------- 1 | nav.toc h1 { 2 | display: none; 3 | } 4 | -------------------------------------------------------------------------------- /src/JuliaZH.jl: -------------------------------------------------------------------------------- 1 | module JuliaZH 2 | 3 | include("basedocs.jl") 4 | 5 | end # module 6 | -------------------------------------------------------------------------------- /docs/src/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/findmyway/JuliaZH.jl/master/docs/src/assets/logo.png -------------------------------------------------------------------------------- /test/runtests.jl: -------------------------------------------------------------------------------- 1 | using JuliaZH 2 | @static if VERSION < v"0.7.0-DEV.2005" 3 | using Base.Test 4 | else 5 | using Test 6 | end 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.jl.cov 2 | *.jl.*.cov 3 | *.jl.mem 4 | 5 | docs/build/ 6 | docs/site/ 7 | 8 | *.ipynb_checkpoints 9 | **/*.ipynb_checkpoints 10 | **/**/*.ipynb_checkpoints 11 | 12 | _*.dat 13 | *.swp 14 | __pycache__/ 15 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | # 中文文档 2 | 3 | 这里是手册等文字部分的文档源文件,所有文档内容都在 `src` 目录下。目前主要结构是: 4 | 5 | - `assets`:素材,logo等 6 | - `base`:Base中的文档自动生成脚本 (需要通过doc string替换来实现翻译) 7 | - `juliacn`: JuliaZH的开发文档 8 | - `manual`:手册 9 | 10 | 如果复制新的文件夹进来请保持master分支的目录结构与julia源代码的master分支中的doc目录一致。 11 | -------------------------------------------------------------------------------- /docs/src/base/libc.md: -------------------------------------------------------------------------------- 1 | # C Standard Library 2 | 3 | ```@docs 4 | Base.Libc.malloc 5 | Base.Libc.calloc 6 | Base.Libc.realloc 7 | Base.Libc.free 8 | Base.Libc.errno 9 | Base.Libc.strerror 10 | Base.Libc.GetLastError 11 | Base.Libc.FormatMessage 12 | Base.Libc.time(::Base.Libc.TmStruct) 13 | Base.Libc.strftime 14 | Base.Libc.strptime 15 | Base.Libc.TmStruct 16 | Base.Libc.flush_cstdio 17 | ``` 18 | -------------------------------------------------------------------------------- /docs/src/base/stacktraces.md: -------------------------------------------------------------------------------- 1 | # StackTraces 2 | 3 | ```@docs 4 | Base.StackTraces.StackFrame 5 | Base.StackTraces.StackTrace 6 | Base.StackTraces.stacktrace 7 | ``` 8 | 9 | The following methods and types in `Base.StackTraces` are not exported and need to be called e.g. 10 | as `StackTraces.lookup(ptr)`. 11 | 12 | ```@docs 13 | Base.StackTraces.lookup 14 | Base.StackTraces.remove_frames! 15 | ``` 16 | -------------------------------------------------------------------------------- /docs/src/base/iterators.md: -------------------------------------------------------------------------------- 1 | # Iteration utilities 2 | 3 | ```@docs 4 | Base.Iterators.Stateful 5 | Base.Iterators.zip 6 | Base.Iterators.enumerate 7 | Base.Iterators.rest 8 | Base.Iterators.countfrom 9 | Base.Iterators.take 10 | Base.Iterators.drop 11 | Base.Iterators.cycle 12 | Base.Iterators.repeated 13 | Base.Iterators.product 14 | Base.Iterators.flatten 15 | Base.Iterators.partition 16 | Base.Iterators.filter 17 | Base.Iterators.reverse 18 | ``` 19 | -------------------------------------------------------------------------------- /docs/src/base/constants.md: -------------------------------------------------------------------------------- 1 | # [Constants](@id lib-constants) 2 | 3 | ```@docs 4 | Core.nothing 5 | Base.PROGRAM_FILE 6 | Base.ARGS 7 | Base.C_NULL 8 | Base.VERSION 9 | Base.LOAD_PATH 10 | Base.Sys.BINDIR 11 | Base.Sys.CPU_THREADS 12 | Base.Sys.WORD_SIZE 13 | Base.Sys.KERNEL 14 | Base.Sys.ARCH 15 | Base.Sys.MACHINE 16 | ``` 17 | 18 | See also: 19 | 20 | * [`stdin`](@ref) 21 | * [`stdout`](@ref) 22 | * [`stderr`](@ref) 23 | * [`ENV`](@ref) 24 | * [`ENDIAN_BOM`](@ref) 25 | * `Libc.MS_ASYNC` 26 | * `Libc.MS_INVALIDATE` 27 | * `Libc.MS_SYNC` 28 | -------------------------------------------------------------------------------- /docs/src/base/parallel.md: -------------------------------------------------------------------------------- 1 | # Tasks 2 | 3 | ```@docs 4 | Core.Task 5 | Base.current_task 6 | Base.istaskdone 7 | Base.istaskstarted 8 | Base.yield 9 | Base.yieldto 10 | Base.task_local_storage(::Any) 11 | Base.task_local_storage(::Any, ::Any) 12 | Base.task_local_storage(::Function, ::Any, ::Any) 13 | Base.Condition 14 | Base.notify 15 | Base.schedule 16 | Base.@task 17 | Base.sleep 18 | Base.Channel 19 | Base.put!(::Channel, ::Any) 20 | Base.take!(::Channel) 21 | Base.isready(::Channel) 22 | Base.fetch(::Channel) 23 | Base.close(::Channel) 24 | Base.bind(c::Channel, task::Task) 25 | Base.asyncmap 26 | Base.asyncmap! 27 | ``` 28 | -------------------------------------------------------------------------------- /docs/src/base/c.md: -------------------------------------------------------------------------------- 1 | # C Interface 2 | 3 | ```@docs 4 | ccall 5 | Core.Intrinsics.cglobal 6 | Base.@cfunction 7 | Base.CFunction 8 | Base.unsafe_convert 9 | Base.cconvert 10 | Base.unsafe_load 11 | Base.unsafe_store! 12 | Base.unsafe_copyto!{T}(::Ptr{T}, ::Ptr{T}, ::Any) 13 | Base.unsafe_copyto!{T}(::Array{T}, ::Any, ::Array{T}, ::Any, ::Any) 14 | Base.copyto! 15 | Base.pointer 16 | Base.unsafe_wrap{T,N}(::Union{Type{Array},Type{Array{T}},Type{Array{T,N}}}, ::Ptr{T}, ::NTuple{N,Int}) 17 | Base.pointer_from_objref 18 | Base.unsafe_pointer_to_objref 19 | Base.disable_sigint 20 | Base.reenable_sigint 21 | Base.systemerror 22 | Core.Ptr 23 | Core.Ref 24 | Base.Cchar 25 | Base.Cuchar 26 | Base.Cshort 27 | Base.Cushort 28 | Base.Cint 29 | Base.Cuint 30 | Base.Clong 31 | Base.Culong 32 | Base.Clonglong 33 | Base.Culonglong 34 | Base.Cintmax_t 35 | Base.Cuintmax_t 36 | Base.Csize_t 37 | Base.Cssize_t 38 | Base.Cptrdiff_t 39 | Base.Cwchar_t 40 | Base.Cfloat 41 | Base.Cdouble 42 | ``` 43 | 44 | # LLVM Interface 45 | 46 | ```@docs 47 | Core.Intrinsics.llvmcall 48 | ``` 49 | -------------------------------------------------------------------------------- /docs/src/base/multi-threading.md: -------------------------------------------------------------------------------- 1 | 2 | # Multi-Threading 3 | 4 | This experimental interface supports Julia's multi-threading capabilities. Types and functions 5 | described here might (and likely will) change in the future. 6 | 7 | ```@docs 8 | Base.Threads.threadid 9 | Base.Threads.nthreads 10 | Base.Threads.@threads 11 | Base.Threads.Atomic 12 | Base.Threads.atomic_cas! 13 | Base.Threads.atomic_xchg! 14 | Base.Threads.atomic_add! 15 | Base.Threads.atomic_sub! 16 | Base.Threads.atomic_and! 17 | Base.Threads.atomic_nand! 18 | Base.Threads.atomic_or! 19 | Base.Threads.atomic_xor! 20 | Base.Threads.atomic_max! 21 | Base.Threads.atomic_min! 22 | Base.Threads.atomic_fence 23 | ``` 24 | 25 | ## ccall using a threadpool (Experimental) 26 | 27 | ```@docs 28 | Base.@threadcall 29 | ``` 30 | 31 | ## Synchronization Primitives 32 | 33 | ```@docs 34 | Base.Threads.AbstractLock 35 | Base.lock 36 | Base.unlock 37 | Base.trylock 38 | Base.islocked 39 | Base.ReentrantLock 40 | Base.Threads.Mutex 41 | Base.Threads.SpinLock 42 | Base.Threads.RecursiveSpinLock 43 | Base.Semaphore 44 | Base.acquire 45 | Base.release 46 | ``` 47 | 48 | -------------------------------------------------------------------------------- /docs/src/juliacn/style-guide.md: -------------------------------------------------------------------------------- 1 | # 翻译格式指引 2 | 3 | 统一的翻译稿件格式有助于日后维护。请在参与翻译之前阅读这个指引,以保证大家的文档格式基本一致。 4 | 5 | ## 原文段落组织 6 | 7 | 英文原文如下方式在Markdown里注释: 8 | 9 | ``` 10 | \`\`\`@raw html 11 | 12 | \`\`\` 13 | ``` 14 | 15 | 中文翻译写在下面。 16 | 17 | ## 格式细则 18 | 19 | 1. 段落英文中的英文两边空格,例如: 20 | 21 | > 不要将它的类型声明为 `Int` 22 | 23 | 2. 专业词汇请用括号注明英文原文,例如 24 | 25 | > 而要使用抽象类型(abstract type) 26 | 27 | 3. 文件链接全部保持原文链接(包括wiki,`@ref`的文档内部交叉引用) 28 | 29 | 4. master分支的文档跟进官方repo的master分支。 30 | 31 | 5. 对于表格, 如果翻译则请按照段落处理 32 | 33 | 34 | ## 提交规则 35 | 36 | - 提交译文时, 请用 pull request (PR) 提交。 对于翻译中不确定的部分, 请在 PR 里指明。 37 | 38 | - 对于含有多个 commit 的 PR, 合并时, 请选择 ``squash and merge`` 。 39 | 40 | ## 书写规范 41 | ### 标点符号 42 | 中文内容请使用半角中文标点符号, 尤其是逗号以及括号, 冒号, 破折号。 对于引号, 如果被引用的内容**包含**英文, 则使用英文引号。 43 | 44 | ### 空格 45 | 译文一律使用空格, 禁止使用 ``Tab``, 仅对注释原文时可以用 ``Tab`` 缩进, 缩进为两个空格。 中文和英文以及数字间应加一个空格。 46 | 47 | ### 粗斜体 48 | 中文部分不应使用斜体, 对于原文斜体部分, 译文里可以酌情修改为粗体。 49 | 50 | ## 内容规范 51 | 力求表达清楚明确, 语句尽量通顺, 请不要逐字翻译, 避免错别字等。 52 | 53 | ### 代码 54 | 只翻译注释, 如果代码简单易懂, 可不翻译。 55 | 56 | ### 专有名词 57 | 如果没有对应或者不确定的专有词汇, 可以先不译, 保留在译文里。 等确定后可批量修改。 58 | 59 | ### 人称代词 60 | 像 "we" 和 "you" 这些词汇一般来说可以不译出来, 或者换个说法。 如果译出来更通顺, 就翻译出来。 61 | -------------------------------------------------------------------------------- /docs/src/base/simd-types.md: -------------------------------------------------------------------------------- 1 | # SIMD Support 2 | 3 | Type `VecElement{T}` is intended for building libraries of SIMD operations. Practical use of it 4 | requires using `llvmcall`. The type is defined as: 5 | 6 | ```julia 7 | struct VecElement{T} 8 | value::T 9 | end 10 | ``` 11 | 12 | It has a special compilation rule: a homogeneous tuple of `VecElement{T}` maps to an LLVM `vector` 13 | type when `T` is a primitive bits type and the tuple length is in the set {2-6,8-10,16}. 14 | 15 | At `-O3`, the compiler *might* automatically vectorize operations on such tuples. For example, 16 | the following program, when compiled with `julia -O3` generates two SIMD addition instructions 17 | (`addps`) on x86 systems: 18 | 19 | ```julia 20 | const m128 = NTuple{4,VecElement{Float32}} 21 | 22 | function add(a::m128, b::m128) 23 | (VecElement(a[1].value+b[1].value), 24 | VecElement(a[2].value+b[2].value), 25 | VecElement(a[3].value+b[3].value), 26 | VecElement(a[4].value+b[4].value)) 27 | end 28 | 29 | triple(c::m128) = add(add(c,c),c) 30 | 31 | code_native(triple,(m128,)) 32 | ``` 33 | 34 | However, since the automatic vectorization cannot be relied upon, future use will mostly be via 35 | libraries that use `llvmcall`. 36 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The JuliaZH.jl package is licensed under the MIT "Expat" License: 2 | 3 | > Copyright (c) 2018: Roger-luo. 4 | > 5 | > Permission is hereby granted, free of charge, to any person obtaining a copy 6 | > of this software and associated documentation files (the "Software"), to deal 7 | > in the Software without restriction, including without limitation the rights 8 | > to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | > copies of the Software, and to permit persons to whom the Software is 10 | > furnished to do so, subject to the following conditions: 11 | > 12 | > The above copyright notice and this permission notice shall be included in all 13 | > copies or substantial portions of the Software. 14 | > 15 | > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | > FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | > SOFTWARE. 22 | > 23 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | ## Documentation: http://docs.travis-ci.com/user/languages/julia/ 2 | language: julia 3 | os: 4 | - linux 5 | - osx 6 | julia: 7 | - 0.7 8 | - nightly 9 | notifications: 10 | email: false 11 | git: 12 | depth: 99999999 13 | 14 | ## uncomment the following lines to allow failures on nightly julia 15 | ## (tests will run but not make your overall status red) 16 | #matrix: 17 | # allow_failures: 18 | # - julia: nightly 19 | 20 | ## uncomment and modify the following lines to manually install system packages 21 | #addons: 22 | # apt: # apt-get for linux 23 | # packages: 24 | # - gfortran 25 | #before_script: # homebrew for mac 26 | # - if [ $TRAVIS_OS_NAME = osx ]; then brew install gcc; fi 27 | 28 | ## uncomment the following lines to override the default test script 29 | #script: 30 | # - julia -e 'Pkg.clone(pwd()); Pkg.build("JuliaZH"); Pkg.test("JuliaZH"; coverage=true)' 31 | after_success: 32 | # # push coverage results to Coveralls 33 | # - julia -e 'cd(Pkg.dir("JuliaZH")); Pkg.add("Coverage"); using Coverage; Coveralls.submit(Coveralls.process_folder())' 34 | # # push coverage results to Codecov 35 | # - julia -e 'cd(Pkg.dir("JuliaZH")); Pkg.add("Coverage"); using Coverage; Codecov.submit(Codecov.process_folder())' 36 | # add Documenter 37 | - julia -e 'using Pkg; Pkg.add("Documenter")' 38 | # push documents to gh-pages 39 | - julia -e 'using Pkg; cd(Pkg.dir("JuliaZH")); include(joinpath("docs", "make.jl"))' 40 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JuliaZH.jl 2 | 3 | [![Build Status](https://travis-ci.org/JuliaCN/JuliaZH.jl.svg?branch=master)](https://travis-ci.org/JuliaCN/JuliaZH.jl) 4 | [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://juliacn.github.io/JuliaZH.jl/stable) 5 | [![](https://img.shields.io/badge/docs-latest-blue.svg)](https://juliacn.github.io/JuliaZH.jl/latest) 6 | 7 | Julia中文文档,中文文档是一个标准的Julia包,可以使用包的安装方式来安装, 8 | 如果你只想查看网页版本请访问[Julia 中文文档页面](https://juliacn.github.io/JuliaZH.jl)。 9 | 10 | ## 使用方法 11 | 12 | 暂未注册在源中,仅支持0.7版本,请通过以下方式获取最新的master分支 13 | 14 | Julia 0.7+ 请使用自带的包管理器安装 15 | 16 | ``` 17 | pkg> dev https://github.com/JuliaCN/JuliaZH.jl.git#master 18 | ``` 19 | 20 | 在你的代码中使用这个包,就能够获得中文版本的文档: 21 | 22 | ```julia 23 | julia> using JuliaZH 24 | 25 | help?> julia 26 | search: JuliaZH 27 | 28 | 欢迎来到Julia 0.7.0-beta2.33. 完整的手册(英文)可以在这里找到 29 | 30 | https://docs.julialang.org/ 31 | 32 | 同样下面的网址也列出了很多的入门教程和课程 33 | 34 | https://julialang.org/learning/ 35 | 36 | 更多中文资料和教程,也请关注Julia中文社区 37 | 38 | https://juliacn.github.io (境内域名 juliacn.com 还在备案中) 39 | 40 | 输入 ?, 然后输入你想要查看帮助文档的函数或者宏名称就可以查看它们的文档。例如?cos, 或者 ?@time 然后按回车键即可。 41 | 42 | 退出REPL之后,重新进入将恢复英文模式。 43 | ``` 44 | 45 | 57 | 58 | ## 贡献文档 59 | 60 | 请阅读[JuliaZH的开发文档](https://juliacn.github.io/JuliaZH.jl/latest/juliacn/style-guide/)并给我们提交PR或者通过issue讨论。 61 | 62 | 所有Julia中文文档的贡献者都可以在[贡献者列表](https://github.com/JuliaCN/JuliaZH.jl/graphs/contributors)中找到。此外也感谢曾经参与 63 | 0.3版本文档的[贡献者们](https://github.com/JuliaCN/julia_zh_cn/graphs/contributors)。 64 | 65 | ## 开源协议 66 | 67 | MIT协议 68 | -------------------------------------------------------------------------------- /docs/src/base/file.md: -------------------------------------------------------------------------------- 1 | # Filesystem 2 | 3 | ```@docs 4 | Base.Filesystem.pwd 5 | Base.Filesystem.cd(::AbstractString) 6 | Base.Filesystem.cd(::Function) 7 | Base.Filesystem.readdir 8 | Base.Filesystem.walkdir 9 | Base.Filesystem.mkdir 10 | Base.Filesystem.mkpath 11 | Base.Filesystem.symlink 12 | Base.Filesystem.readlink 13 | Base.Filesystem.chmod 14 | Base.Filesystem.chown 15 | Base.stat 16 | Base.Filesystem.lstat 17 | Base.Filesystem.ctime 18 | Base.Filesystem.mtime 19 | Base.Filesystem.filemode 20 | Base.Filesystem.filesize 21 | Base.Filesystem.uperm 22 | Base.Filesystem.gperm 23 | Base.Filesystem.operm 24 | Base.Filesystem.cp 25 | Base.download 26 | Base.Filesystem.mv 27 | Base.Filesystem.rm 28 | Base.Filesystem.touch 29 | Base.Filesystem.tempname 30 | Base.Filesystem.tempdir 31 | Base.Filesystem.mktemp(::Any) 32 | Base.Filesystem.mktemp(::Function, ::Any) 33 | Base.Filesystem.mktempdir(::Any) 34 | Base.Filesystem.mktempdir(::Function, ::Any) 35 | Base.Filesystem.isblockdev 36 | Base.Filesystem.ischardev 37 | Base.Filesystem.isdir 38 | Base.Filesystem.isfifo 39 | Base.Filesystem.isfile 40 | Base.Filesystem.islink 41 | Base.Filesystem.ismount 42 | Base.Filesystem.ispath 43 | Base.Filesystem.issetgid 44 | Base.Filesystem.issetuid 45 | Base.Filesystem.issocket 46 | Base.Filesystem.issticky 47 | Base.Filesystem.homedir 48 | Base.Filesystem.dirname 49 | Base.Filesystem.basename 50 | Base.@__FILE__ 51 | Base.@__DIR__ 52 | Base.@__LINE__ 53 | Base.Filesystem.isabspath 54 | Base.Filesystem.isdirpath 55 | Base.Filesystem.joinpath 56 | Base.Filesystem.abspath 57 | Base.Filesystem.normpath 58 | Base.Filesystem.realpath 59 | Base.Filesystem.relpath 60 | Base.Filesystem.expanduser 61 | Base.Filesystem.splitdir 62 | Base.Filesystem.splitdrive 63 | Base.Filesystem.splitext 64 | ``` 65 | -------------------------------------------------------------------------------- /docs/src/base/strings.md: -------------------------------------------------------------------------------- 1 | # [Strings](@id lib-strings) 2 | 3 | ```@docs 4 | Core.AbstractChar 5 | Core.Char 6 | Base.codepoint 7 | Base.length(::AbstractString) 8 | Base.sizeof(::AbstractString) 9 | Base.:*(::Union{AbstractChar, AbstractString}, ::Union{AbstractChar, AbstractString}...) 10 | Base.:^(::AbstractString, ::Integer) 11 | Base.string 12 | Base.repeat(::AbstractString, ::Integer) 13 | Base.repeat(::AbstractChar, ::Integer) 14 | Base.repr(::Any) 15 | Core.String(::AbstractString) 16 | Base.SubString 17 | Base.transcode 18 | Base.unsafe_string 19 | Base.ncodeunits(::AbstractString) 20 | Base.codeunit 21 | Base.codeunits 22 | Base.ascii 23 | Base.@r_str 24 | Base.SubstitutionString 25 | Base.@s_str 26 | Base.@raw_str 27 | Base.Docs.@html_str 28 | Base.Docs.@text_str 29 | Base.isvalid(::Any) 30 | Base.isvalid(::Any, ::Any) 31 | Base.isvalid(::AbstractString, ::Integer) 32 | Base.match 33 | Base.eachmatch 34 | Base.isless(::AbstractString, ::AbstractString) 35 | Base.:(==)(::AbstractString, ::AbstractString) 36 | Base.cmp(::AbstractString, ::AbstractString) 37 | Base.lpad 38 | Base.rpad 39 | Base.findfirst(::AbstractString, ::AbstractString) 40 | Base.findnext(::AbstractString, ::AbstractString, ::Integer) 41 | Base.findlast(::AbstractString, ::AbstractString) 42 | Base.findprev(::AbstractString, ::AbstractString, ::Integer) 43 | Base.occursin 44 | Base.reverse(::Union{String,SubString{String}}) 45 | Base.replace(s::AbstractString, ::Pair) 46 | Base.split 47 | Base.rsplit 48 | Base.strip 49 | Base.lstrip 50 | Base.rstrip 51 | Base.startswith 52 | Base.endswith 53 | Base.first(::AbstractString, ::Integer) 54 | Base.last(::AbstractString, ::Integer) 55 | Base.uppercase 56 | Base.lowercase 57 | Base.titlecase 58 | Base.uppercasefirst 59 | Base.lowercasefirst 60 | Base.join 61 | Base.chop 62 | Base.chomp 63 | Base.thisind 64 | Base.nextind 65 | Base.prevind 66 | Base.textwidth 67 | Base.isascii 68 | Base.iscntrl 69 | Base.isdigit 70 | Base.isletter 71 | Base.islowercase 72 | Base.isnumeric 73 | Base.isprint 74 | Base.ispunct 75 | Base.isspace 76 | Base.isuppercase 77 | Base.isxdigit 78 | Core.Symbol 79 | Base.escape_string 80 | Base.unescape_string 81 | ``` 82 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | environment: 2 | matrix: 3 | - JULIA_URL: "https://julialang-s3.julialang.org/bin/winnt/x86/0.6/julia-0.6-latest-win32.exe" 4 | - JULIA_URL: "https://julialang-s3.julialang.org/bin/winnt/x64/0.6/julia-0.6-latest-win64.exe" 5 | - JULIA_URL: "https://julialangnightlies-s3.julialang.org/bin/winnt/x86/julia-latest-win32.exe" 6 | - JULIA_URL: "https://julialangnightlies-s3.julialang.org/bin/winnt/x64/julia-latest-win64.exe" 7 | 8 | ## uncomment the following lines to allow failures on nightly julia 9 | ## (tests will run but not make your overall status red) 10 | #matrix: 11 | # allow_failures: 12 | # - JULIA_URL: "https://julialangnightlies-s3.julialang.org/bin/winnt/x86/julia-latest-win32.exe" 13 | # - JULIA_URL: "https://julialangnightlies-s3.julialang.org/bin/winnt/x64/julia-latest-win64.exe" 14 | 15 | branches: 16 | only: 17 | - master 18 | - /release-.*/ 19 | 20 | notifications: 21 | - provider: Email 22 | on_build_success: false 23 | on_build_failure: false 24 | on_build_status_changed: false 25 | 26 | install: 27 | - ps: "[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12" 28 | # If there's a newer build queued for the same PR, cancel this one 29 | - ps: if ($env:APPVEYOR_PULL_REQUEST_NUMBER -and $env:APPVEYOR_BUILD_NUMBER -ne ((Invoke-RestMethod ` 30 | https://ci.appveyor.com/api/projects/$env:APPVEYOR_ACCOUNT_NAME/$env:APPVEYOR_PROJECT_SLUG/history?recordsNumber=50).builds | ` 31 | Where-Object pullRequestId -eq $env:APPVEYOR_PULL_REQUEST_NUMBER)[0].buildNumber) { ` 32 | throw "There are newer queued builds for this pull request, failing early." } 33 | # Download most recent Julia Windows binary 34 | - ps: (new-object net.webclient).DownloadFile( 35 | $env:JULIA_URL, 36 | "C:\projects\julia-binary.exe") 37 | # Run installer silently, output to C:\projects\julia 38 | - C:\projects\julia-binary.exe /S /D=C:\projects\julia 39 | 40 | build_script: 41 | # Need to convert from shallow to complete for Pkg.clone to work 42 | - IF EXIST .git\shallow (git fetch --unshallow) 43 | - C:\projects\julia\bin\julia -e "versioninfo(); 44 | Pkg.clone(pwd(), \"JuliaZH\"); Pkg.build(\"JuliaZH\")" 45 | 46 | test_script: 47 | - C:\projects\julia\bin\julia -e "Pkg.test(\"JuliaZH\")" 48 | -------------------------------------------------------------------------------- /docs/src/base/numbers.md: -------------------------------------------------------------------------------- 1 | # [Numbers](@id lib-numbers) 2 | 3 | ## Standard Numeric Types 4 | 5 | ### Abstract number types 6 | 7 | ```@docs 8 | Core.Number 9 | Core.Real 10 | Core.AbstractFloat 11 | Core.Integer 12 | Core.Signed 13 | Core.Unsigned 14 | Base.AbstractIrrational 15 | ``` 16 | 17 | ### Concrete number types 18 | 19 | ```@docs 20 | Core.Float16 21 | Core.Float32 22 | Core.Float64 23 | Base.BigFloat 24 | Core.Bool 25 | Core.Int8 26 | Core.UInt8 27 | Core.Int16 28 | Core.UInt16 29 | Core.Int32 30 | Core.UInt32 31 | Core.Int64 32 | Core.UInt64 33 | Core.Int128 34 | Core.UInt128 35 | Base.BigInt 36 | Base.Complex 37 | Base.Rational 38 | Base.Irrational 39 | ``` 40 | 41 | ## Data Formats 42 | 43 | ```@docs 44 | Base.digits 45 | Base.digits! 46 | Base.bitstring 47 | Base.parse 48 | Base.tryparse 49 | Base.big 50 | Base.signed 51 | Base.unsigned 52 | Base.float(::Any) 53 | Base.Math.significand 54 | Base.Math.exponent 55 | Base.complex(::Complex) 56 | Base.bswap 57 | Base.hex2bytes 58 | Base.hex2bytes! 59 | Base.bytes2hex 60 | ``` 61 | 62 | ## General Number Functions and Constants 63 | 64 | ```@docs 65 | Base.one 66 | Base.oneunit 67 | Base.zero 68 | Base.im 69 | Base.MathConstants.pi 70 | Base.MathConstants.ℯ 71 | Base.MathConstants.catalan 72 | Base.MathConstants.eulergamma 73 | Base.MathConstants.golden 74 | Base.Inf 75 | Base.Inf32 76 | Base.Inf16 77 | Base.NaN 78 | Base.NaN32 79 | Base.NaN16 80 | Base.issubnormal 81 | Base.isfinite 82 | Base.isinf 83 | Base.isnan 84 | Base.iszero 85 | Base.isone 86 | Base.nextfloat 87 | Base.prevfloat 88 | Base.isinteger 89 | Base.isreal 90 | Core.Float32(::Any) 91 | Core.Float64(::Any) 92 | Base.GMP.BigInt(::Any) 93 | Base.MPFR.BigFloat(::Any) 94 | Base.Rounding.rounding 95 | Base.Rounding.setrounding(::Type, ::Any) 96 | Base.Rounding.setrounding(::Function, ::Type, ::RoundingMode) 97 | Base.Rounding.get_zero_subnormals 98 | Base.Rounding.set_zero_subnormals 99 | ``` 100 | 101 | ### Integers 102 | 103 | ```@docs 104 | Base.count_ones 105 | Base.count_zeros 106 | Base.leading_zeros 107 | Base.leading_ones 108 | Base.trailing_zeros 109 | Base.trailing_ones 110 | Base.isodd 111 | Base.iseven 112 | ``` 113 | 114 | ## BigFloats 115 | 116 | The [`BigFloat`](@ref) type implements arbitrary-precision floating-point arithmetic using 117 | the [GNU MPFR library](http://www.mpfr.org/). 118 | 119 | ```@docs 120 | Base.precision 121 | Base.MPFR.precision(::Type{BigFloat}) 122 | Base.MPFR.setprecision 123 | Base.MPFR.BigFloat(x, prec::Int) 124 | BigFloat(x::Union{Integer, AbstractFloat, String}, rounding::RoundingMode) 125 | Base.MPFR.BigFloat(x, prec::Int, rounding::RoundingMode) 126 | Base.MPFR.BigFloat(x::String) 127 | ``` 128 | -------------------------------------------------------------------------------- /docs/src/base/math.md: -------------------------------------------------------------------------------- 1 | # Mathematics 2 | 3 | ## [Mathematical Operators](@id math-ops) 4 | 5 | ```@docs 6 | Base.:-(::Any) 7 | Base.:(+) 8 | Base.:-(::Any, ::Any) 9 | Base.:*(::Any, ::Any...) 10 | Base.:(/) 11 | Base.:\(::Any, ::Any) 12 | Base.:^(::Number, ::Number) 13 | Base.fma 14 | Base.muladd 15 | Base.inv(::Number) 16 | Base.div 17 | Base.fld 18 | Base.cld 19 | Base.mod 20 | Base.rem 21 | Base.rem2pi 22 | Base.Math.mod2pi 23 | Base.divrem 24 | Base.fldmod 25 | Base.fld1 26 | Base.mod1 27 | Base.fldmod1 28 | Base.:(//) 29 | Base.rationalize 30 | Base.numerator 31 | Base.denominator 32 | Base.:(<<) 33 | Base.:(>>) 34 | Base.:(>>>) 35 | Base.:(:) 36 | Base.range 37 | Base.OneTo 38 | Base.StepRangeLen 39 | Base.:(==) 40 | Base.:(!=) 41 | Base.:(!==) 42 | Base.:(<) 43 | Base.:(<=) 44 | Base.:(>) 45 | Base.:(>=) 46 | Base.cmp 47 | Base.:(~) 48 | Base.:(&) 49 | Base.:(|) 50 | Base.xor 51 | Base.:(!) 52 | && 53 | || 54 | ``` 55 | 56 | ## Mathematical Functions 57 | 58 | ```@docs 59 | Base.isapprox 60 | Base.sin(::Number) 61 | Base.cos(::Number) 62 | Base.sincos(::Float64) 63 | Base.tan(::Number) 64 | Base.Math.sind 65 | Base.Math.cosd 66 | Base.Math.tand 67 | Base.Math.sinpi 68 | Base.Math.cospi 69 | Base.sinh(::Number) 70 | Base.cosh(::Number) 71 | Base.tanh(::Number) 72 | Base.asin(::Number) 73 | Base.acos(::Number) 74 | Base.atan(::Number) 75 | Base.Math.asind 76 | Base.Math.acosd 77 | Base.Math.atand 78 | Base.Math.sec(::Number) 79 | Base.Math.csc(::Number) 80 | Base.Math.cot(::Number) 81 | Base.Math.secd 82 | Base.Math.cscd 83 | Base.Math.cotd 84 | Base.Math.asec(::Number) 85 | Base.Math.acsc(::Number) 86 | Base.Math.acot(::Number) 87 | Base.Math.asecd 88 | Base.Math.acscd 89 | Base.Math.acotd 90 | Base.Math.sech(::Number) 91 | Base.Math.csch(::Number) 92 | Base.Math.coth(::Number) 93 | Base.asinh(::Number) 94 | Base.acosh(::Number) 95 | Base.atanh(::Number) 96 | Base.Math.asech(::Number) 97 | Base.Math.acsch(::Number) 98 | Base.Math.acoth(::Number) 99 | Base.Math.sinc 100 | Base.Math.cosc 101 | Base.Math.deg2rad 102 | Base.Math.rad2deg 103 | Base.Math.hypot 104 | Base.log(::Number) 105 | Base.log(::Number, ::Number) 106 | Base.log2 107 | Base.log10 108 | Base.log1p 109 | Base.Math.frexp 110 | Base.exp(::Float64) 111 | Base.exp2 112 | Base.exp10 113 | Base.Math.ldexp 114 | Base.Math.modf 115 | Base.expm1 116 | Base.round(::Type, ::Any) 117 | Base.Rounding.RoundingMode 118 | Base.Rounding.RoundNearest 119 | Base.Rounding.RoundNearestTiesAway 120 | Base.Rounding.RoundNearestTiesUp 121 | Base.Rounding.RoundToZero 122 | Base.Rounding.RoundUp 123 | Base.Rounding.RoundDown 124 | Base.round(::Complex{<: AbstractFloat}, ::RoundingMode, ::RoundingMode) 125 | Base.ceil 126 | Base.floor 127 | Base.trunc 128 | Base.unsafe_trunc 129 | Base.min 130 | Base.max 131 | Base.minmax 132 | Base.Math.clamp 133 | Base.Math.clamp! 134 | Base.abs 135 | Base.Checked.checked_abs 136 | Base.Checked.checked_neg 137 | Base.Checked.checked_add 138 | Base.Checked.checked_sub 139 | Base.Checked.checked_mul 140 | Base.Checked.checked_div 141 | Base.Checked.checked_rem 142 | Base.Checked.checked_fld 143 | Base.Checked.checked_mod 144 | Base.Checked.checked_cld 145 | Base.Checked.add_with_overflow 146 | Base.Checked.sub_with_overflow 147 | Base.Checked.mul_with_overflow 148 | Base.abs2 149 | Base.copysign 150 | Base.sign 151 | Base.signbit 152 | Base.flipsign 153 | Base.sqrt(::Real) 154 | Base.isqrt 155 | Base.Math.cbrt 156 | Base.real(::Complex) 157 | Base.imag 158 | Base.reim 159 | Base.conj 160 | Base.angle 161 | Base.cis 162 | Base.binomial 163 | Base.factorial 164 | Base.gcd 165 | Base.lcm 166 | Base.gcdx 167 | Base.ispow2 168 | Base.nextpow2 169 | Base.prevpow2 170 | Base.nextpow 171 | Base.prevpow 172 | Base.nextprod 173 | Base.invmod 174 | Base.powermod 175 | Base.ndigits 176 | Base.widemul 177 | Base.Math.@evalpoly 178 | Base.FastMath.@fastmath 179 | ``` 180 | -------------------------------------------------------------------------------- /docs/make.jl: -------------------------------------------------------------------------------- 1 | using Documenter, JuliaZH 2 | 3 | const PAGES = [ 4 | "主页" => "index.md", 5 | # hide("NEWS.md"), 6 | "手册" => [ 7 | "manual/getting-started.md", 8 | "manual/variables.md", 9 | "manual/integers-and-floating-point-numbers.md", 10 | # "manual/mathematical-operations.md", 11 | "manual/complex-and-rational-numbers.md", 12 | "manual/strings.md", 13 | # "manual/functions.md", 14 | # "manual/control-flow.md", 15 | # "manual/variables-and-scoping.md", 16 | # "manual/types.md", 17 | # "manual/methods.md", 18 | # "manual/constructors.md", 19 | # "manual/conversion-and-promotion.md", 20 | # "manual/interfaces.md", 21 | # "manual/modules.md", 22 | # "manual/documentation.md", 23 | # "manual/metaprogramming.md", 24 | # "manual/arrays.md", 25 | # "manual/missing.md", 26 | # "manual/networking-and-streams.md", 27 | "manual/parallel-computing.md", 28 | # "manual/running-external-programs.md", 29 | # "manual/calling-c-and-fortran-code.md", 30 | # "manual/handling-operating-system-variation.md", 31 | # "manual/environment-variables.md", 32 | # "manual/embedding.md", 33 | # "manual/code-loading.md", 34 | # "manual/profile.md", 35 | # "manual/stacktraces.md", 36 | # "manual/performance-tips.md", 37 | # "manual/workflow-tips.md", 38 | "manual/style-guide.md", 39 | # "manual/faq.md", 40 | # "manual/noteworthy-differences.md", 41 | # "manual/unicode-input.md", 42 | ], 43 | "基础组件" => [ 44 | "base/base.md", 45 | "base/collections.md", 46 | "base/math.md", 47 | "base/numbers.md", 48 | "base/strings.md", 49 | "base/arrays.md", 50 | "base/parallel.md", 51 | "base/multi-threading.md", 52 | "base/constants.md", 53 | "base/file.md", 54 | "base/io-network.md", 55 | "base/punctuation.md", 56 | "base/sort.md", 57 | "base/iterators.md", 58 | "base/c.md", 59 | "base/libc.md", 60 | "base/stacktraces.md", 61 | "base/simd-types.md", 62 | ], 63 | # "Standard Library" => 64 | # [stdlib.targetfile for stdlib in STDLIB_DOCS], 65 | # "Developer Documentation" => [ 66 | # "devdocs/reflection.md", 67 | # "Documentation of Julia's Internals" => [ 68 | # "devdocs/init.md", 69 | # "devdocs/ast.md", 70 | # "devdocs/types.md", 71 | # "devdocs/object.md", 72 | # "devdocs/eval.md", 73 | # "devdocs/callconv.md", 74 | # "devdocs/compiler.md", 75 | # "devdocs/functions.md", 76 | # "devdocs/cartesian.md", 77 | # "devdocs/meta.md", 78 | # "devdocs/subarrays.md", 79 | # "devdocs/sysimg.md", 80 | # "devdocs/llvm.md", 81 | # "devdocs/stdio.md", 82 | # "devdocs/boundscheck.md", 83 | # "devdocs/locks.md", 84 | # "devdocs/offset-arrays.md", 85 | # "devdocs/require.md", 86 | # "devdocs/inference.md", 87 | # ], 88 | # "Developing/debugging Julia's C code" => [ 89 | # "devdocs/backtraces.md", 90 | # "devdocs/debuggingtips.md", 91 | # "devdocs/valgrind.md", 92 | # "devdocs/sanitizers.md", 93 | # ] 94 | # ], 95 | "中文文档开发" => [ 96 | "juliacn/style-guide.md", 97 | ] 98 | ] 99 | 100 | # make documents 101 | makedocs(modules=[JuliaZH, Base, Core], 102 | clean=false, 103 | doctest=false, 104 | sitename="Julia中文文档", 105 | checkdocs=:none, # we do not have translation of stdlib now 106 | linkcheck=false, # !("skiplinks" in ARGS), 107 | format="pdf" in ARGS ? :latex : :html, 108 | authors="Julia中文社区", 109 | analytics="UA-89508993-1", 110 | pages=PAGES, 111 | html_prettyurls=!("local" in ARGS), 112 | html_canonical="http://docs.juliacn.com/latest/",) 113 | 114 | deploydocs(repo="github.com/findmyway/JuliaZH.jl.git", 115 | target="build", 116 | julia="0.7", 117 | deps=nothing, 118 | make=nothing,) 119 | -------------------------------------------------------------------------------- /docs/src/base/arrays.md: -------------------------------------------------------------------------------- 1 | # [数组](@id lib-arrays) 2 | 3 | 4 | ## 构造器和类型 5 | 6 | ```@raw html 7 | 8 | ``` 9 | 10 | 11 | 12 | ```@docs 13 | Core.AbstractArray 14 | Base.AbstractVector 15 | Base.AbstractMatrix 16 | Base.AbstractVecOrMat 17 | Core.Array 18 | Core.Array(::UndefInitializer, ::Any) 19 | Core.Array(::Nothing, ::Any) 20 | Core.Array(::Missing, ::Any) 21 | Core.UndefInitializer 22 | Core.undef 23 | Base.Vector 24 | Base.Vector(::UndefInitializer, ::Any) 25 | Base.Vector(::Nothing, ::Any) 26 | Base.Vector(::Missing, ::Any) 27 | Base.Matrix 28 | Base.Matrix(::UndefInitializer, ::Any, ::Any) 29 | Base.Matrix(::Nothing, ::Any, ::Any) 30 | Base.Matrix(::Missing, ::Any, ::Any) 31 | Base.VecOrMat 32 | Core.DenseArray 33 | Base.DenseVector 34 | Base.DenseMatrix 35 | Base.DenseVecOrMat 36 | Base.getindex(::Type, ::Any...) 37 | Base.zeros 38 | Base.ones 39 | Base.BitArray 40 | Base.BitArray(::UndefInitializer, ::Integer...) 41 | Base.BitArray(::Any) 42 | Base.trues 43 | Base.falses 44 | Base.fill 45 | Base.fill! 46 | Base.similar 47 | ``` 48 | 49 | ## 基本函数 50 | 51 | ```@raw html 52 | 53 | ``` 54 | 55 | ```@docs 56 | Base.ndims 57 | Base.size 58 | Base.axes(::Any) 59 | Base.axes(::AbstractArray, ::Any) 60 | Base.length(::AbstractArray) 61 | Base.eachindex 62 | Base.IndexStyle 63 | Base.conj! 64 | Base.stride 65 | Base.strides 66 | ``` 67 | 68 | ## 广播和向量化 69 | 70 | ```@raw html 71 | 72 | ``` 73 | 74 | 参见[dot syntax for vectorizing functions](@ref man-vectorized);例如,`f.(args...)`隐式 75 | 调用了 `broadcast(f, args...)` 。与其依赖类似于作用在数组上的`sin`这样的“向量化的”函数方法,你应当使用 76 | `sin.(a)`来通过`broadcast`向量化这个操作。 77 | 78 | ```@raw html 79 | 83 | ``` 84 | 85 | ```@docs 86 | Base.broadcast 87 | Base.Broadcast.broadcast! 88 | Base.@__dot__ 89 | ``` 90 | 91 | For specializing broadcast on custom types, see 92 | ```@docs 93 | Base.BroadcastStyle 94 | Base.broadcast_axes 95 | Base.Broadcast.AbstractArrayStyle 96 | Base.Broadcast.ArrayStyle 97 | Base.Broadcast.DefaultArrayStyle 98 | Base.Broadcast.broadcastable 99 | ``` 100 | 101 | ## 索引和赋值 102 | 103 | ```@raw html 104 | 105 | ``` 106 | 107 | ```@docs 108 | Base.getindex(::AbstractArray, ::Any...) 109 | Base.setindex!(::AbstractArray, ::Any, ::Any...) 110 | Base.copyto!(::AbstractArray, ::CartesianIndices, ::AbstractArray, ::CartesianIndices) 111 | Base.isassigned 112 | Base.Colon 113 | Base.CartesianIndex 114 | Base.CartesianIndices 115 | Base.Dims 116 | Base.LinearIndices 117 | Base.to_indices 118 | Base.checkbounds 119 | Base.checkindex 120 | ``` 121 | 122 | ## 查看(Views,SubArrays和其它查看类型) 123 | 124 | ```@raw html 125 | 126 | ``` 127 | 128 | ```@docs 129 | Base.view 130 | Base.@view 131 | Base.@views 132 | Base.parent 133 | Base.parentindices 134 | Base.selectdim 135 | Base.reinterpret 136 | Base.reshape 137 | Base.squeeze 138 | Base.vec 139 | ``` 140 | 141 | ## 连接和置换 142 | 143 | ```@raw html 144 | 145 | ``` 146 | 147 | ```@docs 148 | Base.cat 149 | Base.vcat 150 | Base.hcat 151 | Base.hvcat 152 | Base.vect 153 | Base.circshift 154 | Base.circshift! 155 | Base.circcopy! 156 | Base.findall(::Any) 157 | Base.findall(::Function, ::Any) 158 | Base.findfirst(::Any) 159 | Base.findfirst(::Function, ::Any) 160 | Base.findlast(::Any) 161 | Base.findlast(::Function, ::Any) 162 | Base.findnext(::Any, ::Integer) 163 | Base.findnext(::Function, ::Any, ::Integer) 164 | Base.findprev(::Any, ::Integer) 165 | Base.findprev(::Function, ::Any, ::Integer) 166 | Base.permutedims 167 | Base.permutedims! 168 | Base.PermutedDimsArray 169 | Base.promote_shape 170 | ``` 171 | 172 | ## 数组函数 173 | 174 | ```@raw html 175 | 176 | ``` 177 | 178 | ```@docs 179 | Base.accumulate 180 | Base.accumulate! 181 | Base.cumprod 182 | Base.cumprod! 183 | Base.cumsum 184 | Base.cumsum! 185 | Base.diff 186 | Base.repeat 187 | Base.rot180 188 | Base.rotl90 189 | Base.rotr90 190 | Base.mapslices 191 | ``` 192 | 193 | ## 组合 194 | 195 | ```@raw html 196 | 197 | ``` 198 | 199 | ```@docs 200 | Base.invperm 201 | Base.isperm 202 | Base.permute!(::Any, ::AbstractVector) 203 | Base.invpermute! 204 | Base.reverse(::AbstractVector; kwargs...) 205 | Base.reverseind 206 | Base.reverse! 207 | ``` 208 | -------------------------------------------------------------------------------- /docs/src/base/io-network.md: -------------------------------------------------------------------------------- 1 | # I/O 和网络(Network) 2 | 3 | ```@raw html 4 | 5 | ``` 6 | 7 | ## General I/O 8 | 9 | ```@docs 10 | Base.stdout 11 | Base.stderr 12 | Base.stdin 13 | Base.open 14 | Base.IOBuffer 15 | Base.take!(::Base.GenericIOBuffer) 16 | Base.fdio 17 | Base.flush 18 | Base.close 19 | Base.write 20 | Base.read 21 | Base.read! 22 | Base.readbytes! 23 | Base.unsafe_read 24 | Base.unsafe_write 25 | Base.position 26 | Base.seek 27 | Base.seekstart 28 | Base.seekend 29 | Base.skip 30 | Base.mark 31 | Base.unmark 32 | Base.reset 33 | Base.ismarked 34 | Base.eof 35 | Base.isreadonly 36 | Base.iswritable 37 | Base.isreadable 38 | Base.isopen 39 | Base.Grisu.print_shortest 40 | Base.fd 41 | Base.redirect_stdout 42 | Base.redirect_stdout(::Function, ::Any) 43 | Base.redirect_stderr 44 | Base.redirect_stderr(::Function, ::Any) 45 | Base.redirect_stdin 46 | Base.redirect_stdin(::Function, ::Any) 47 | Base.readchomp 48 | Base.truncate 49 | Base.skipchars 50 | Base.countlines 51 | Base.PipeBuffer 52 | Base.readavailable 53 | Base.IOContext 54 | Base.IOContext(::IO, ::Pair) 55 | Base.IOContext(::IO, ::IOContext) 56 | ``` 57 | 58 | ## Text I/O 59 | 60 | ```@docs 61 | Base.show(::Any) 62 | Base.summary 63 | Base.print 64 | Base.println 65 | Base.printstyled 66 | Base.sprint 67 | Base.showerror 68 | Base.dump 69 | Meta.@dump 70 | Base.readline 71 | Base.readuntil 72 | Base.readlines 73 | Base.eachline 74 | Base.displaysize 75 | ``` 76 | 77 | ## Multimedia I/O 78 | 79 | Just as text output is performed by [`print`](@ref) and user-defined types can indicate their textual 80 | representation by overloading [`show`](@ref), Julia provides a standardized mechanism for rich multimedia 81 | output (such as images, formatted text, or even audio and video), consisting of three parts: 82 | 83 | * A function [`display(x)`](@ref) to request the richest available multimedia display of a Julia object 84 | `x` (with a plain-text fallback). 85 | * Overloading [`show`](@ref) allows one to indicate arbitrary multimedia representations (keyed by standard 86 | MIME types) of user-defined types. 87 | * Multimedia-capable display backends may be registered by subclassing a generic `AbstractDisplay` type 88 | and pushing them onto a stack of display backends via [`pushdisplay`](@ref). 89 | 90 | The base Julia runtime provides only plain-text display, but richer displays may be enabled by 91 | loading external modules or by using graphical Julia environments (such as the IPython-based IJulia 92 | notebook). 93 | 94 | ```@docs 95 | Base.Multimedia.display 96 | Base.Multimedia.redisplay 97 | Base.Multimedia.displayable 98 | Base.show(::Any, ::Any, ::Any) 99 | Base.Multimedia.showable 100 | Base.repr(::MIME, ::Any) 101 | ``` 102 | 103 | As mentioned above, one can also define new display backends. For example, a module that can display 104 | PNG images in a window can register this capability with Julia, so that calling [`display(x)`](@ref) on 105 | types with PNG representations will automatically display the image using the module's window. 106 | 107 | In order to define a new display backend, one should first create a subtype `D` of the abstract 108 | class `AbstractDisplay`. Then, for each MIME type (`mime` string) that can be displayed on `D`, one should 109 | define a function `display(d::D, ::MIME"mime", x) = ...` that displays `x` as that MIME type, 110 | usually by calling [`show(io, mime, x)`](@ref) or [`repr(io, mime, x)`](@ref). 111 | A `MethodError` should be thrown if `x` cannot be displayed 112 | as that MIME type; this is automatic if one calls `show` or `repr`. Finally, one should define a function 113 | `display(d::D, x)` that queries [`showable(mime, x)`](@ref) for the `mime` types supported by `D` 114 | and displays the "best" one; a `MethodError` should be thrown if no supported MIME types are found 115 | for `x`. Similarly, some subtypes may wish to override [`redisplay(d::D, ...)`](@ref Base.Multimedia.redisplay). (Again, one should 116 | `import Base.display` to add new methods to `display`.) The return values of these functions are 117 | up to the implementation (since in some cases it may be useful to return a display "handle" of 118 | some type). The display functions for `D` can then be called directly, but they can also be invoked 119 | automatically from [`display(x)`](@ref) simply by pushing a new display onto the display-backend stack 120 | with: 121 | 122 | ```@docs 123 | Base.Multimedia.pushdisplay 124 | Base.Multimedia.popdisplay 125 | Base.Multimedia.TextDisplay 126 | Base.Multimedia.istextmime 127 | ``` 128 | 129 | ## Network I/O 130 | 131 | ```@docs 132 | Base.bytesavailable 133 | Base.ntoh 134 | Base.hton 135 | Base.ltoh 136 | Base.htol 137 | Base.ENDIAN_BOM 138 | ``` 139 | -------------------------------------------------------------------------------- /docs/src/base/punctuation.md: -------------------------------------------------------------------------------- 1 | # Punctuation 2 | 3 | Extended documentation for mathematical symbols & functions is [here](@ref math-ops). 4 | 5 | | symbol | meaning | 6 | |:----------- |:----------------------------------------------------------------------------------------------------------------------------------------------- | 7 | | `@m` | invoke macro `m`; followed by space-separated expressions | 8 | | `!` | prefix "not" (logical negation) operator | 9 | | `a!( )` | at the end of a function name, `!` is used as a convention to indicate that a function modifies its argument(s) | 10 | | `#` | begin single line comment | 11 | | `#=` | begin multi-line comment (these are nestable) | 12 | | `=#` | end multi-line comment | 13 | | `$` | string and expression interpolation | 14 | | `%` | remainder operator | 15 | | `^` | exponent operator | 16 | | `&` | bitwise and | 17 | | `&&` | short-circuiting boolean and | 18 | | `\|` | bitwise or | 19 | | `\|\|` | short-circuiting boolean or | 20 | | `⊻` | bitwise xor operator | 21 | | `*` | multiply, or matrix multiply | 22 | | `()` | the empty tuple | 23 | | `~` | bitwise not operator | 24 | | `\` | backslash operator | 25 | | `'` | complex transpose operator Aᴴ | 26 | | `a[]` | array indexing (calling [`getindex`](@ref) or [`setindex!`](@ref)) | 27 | | `[,]` | vector literal constructor (calling [`vect`](@ref Base.vect)) | 28 | | `[;]` | vertical concatenation (calling [`vcat`](@ref) or [`hvcat`](@ref)) | 29 | | `[   ]` | with space-separated expressions, horizontal concatenation (calling [`hcat`](@ref) or [`hvcat`](@ref)) | 30 | | `T{ }` | parametric type instantiation | 31 | | `;` | statement separator | 32 | | `,` | separate function arguments or tuple components | 33 | | `?` | 3-argument conditional operator (used like: `conditional ? if_true : if_false`) | 34 | | `""` | delimit string literals | 35 | | `''` | delimit character literals | 36 | | ``` ` ` ``` | delimit external process (command) specifications | 37 | | `...` | splice arguments into a function call or declare a varargs function | 38 | | `.` | access named fields in objects/modules (calling [`getproperty`](@ref Base.getproperty) or [`setproperty!`](@ref Base.setproperty!)), also prefixes elementwise function calls (calling [`broadcast`](@ref)) | 39 | | `a:b` | range a, a+1, a+2, ..., b | 40 | | `a:s:b` | range a, a+s, a+2s, ..., b | 41 | | `:` | index an entire dimension (firstindex:lastindex), see [`Colon`](@ref)) | 42 | | `::` | type annotation or [`typeassert`](@ref), depending on context | 43 | | `:( )` | quoted expression | 44 | | `:a` | symbol a | 45 | | `<:` | [`subtype operator`](@ref <:) | 46 | | `>:` | [`supertype operator`](@ref >:) (reverse of subtype operator) | 47 | | `===` | [`egal comparison operator`](@ref ===) | 48 | -------------------------------------------------------------------------------- /docs/src/base/sort.md: -------------------------------------------------------------------------------- 1 | # Sorting and Related Functions 2 | 3 | Julia has an extensive, flexible API for sorting and interacting with already-sorted arrays of 4 | values. By default, Julia picks reasonable algorithms and sorts in standard ascending order: 5 | 6 | ```jldoctest 7 | julia> sort([2,3,1]) 8 | 3-element Array{Int64,1}: 9 | 1 10 | 2 11 | 3 12 | ``` 13 | 14 | You can easily sort in reverse order as well: 15 | 16 | ```jldoctest 17 | julia> sort([2,3,1], rev=true) 18 | 3-element Array{Int64,1}: 19 | 3 20 | 2 21 | 1 22 | ``` 23 | 24 | To sort an array in-place, use the "bang" version of the sort function: 25 | 26 | ```jldoctest 27 | julia> a = [2,3,1]; 28 | 29 | julia> sort!(a); 30 | 31 | julia> a 32 | 3-element Array{Int64,1}: 33 | 1 34 | 2 35 | 3 36 | ``` 37 | 38 | Instead of directly sorting an array, you can compute a permutation of the array's indices that 39 | puts the array into sorted order: 40 | 41 | ```julia-repl 42 | julia> v = randn(5) 43 | 5-element Array{Float64,1}: 44 | 0.297288 45 | 0.382396 46 | -0.597634 47 | -0.0104452 48 | -0.839027 49 | 50 | julia> p = sortperm(v) 51 | 5-element Array{Int64,1}: 52 | 5 53 | 3 54 | 4 55 | 1 56 | 2 57 | 58 | julia> v[p] 59 | 5-element Array{Float64,1}: 60 | -0.839027 61 | -0.597634 62 | -0.0104452 63 | 0.297288 64 | 0.382396 65 | ``` 66 | 67 | Arrays can easily be sorted according to an arbitrary transformation of their values: 68 | 69 | ```julia-repl 70 | julia> sort(v, by=abs) 71 | 5-element Array{Float64,1}: 72 | -0.0104452 73 | 0.297288 74 | 0.382396 75 | -0.597634 76 | -0.839027 77 | ``` 78 | 79 | Or in reverse order by a transformation: 80 | 81 | ```julia-repl 82 | julia> sort(v, by=abs, rev=true) 83 | 5-element Array{Float64,1}: 84 | -0.839027 85 | -0.597634 86 | 0.382396 87 | 0.297288 88 | -0.0104452 89 | ``` 90 | 91 | If needed, the sorting algorithm can be chosen: 92 | 93 | ```julia-repl 94 | julia> sort(v, alg=InsertionSort) 95 | 5-element Array{Float64,1}: 96 | -0.839027 97 | -0.597634 98 | -0.0104452 99 | 0.297288 100 | 0.382396 101 | ``` 102 | 103 | All the sorting and order related functions rely on a "less than" relation defining a total order 104 | on the values to be manipulated. The `isless` function is invoked by default, but the relation 105 | can be specified via the `lt` keyword. 106 | 107 | ## Sorting Functions 108 | 109 | ```@docs 110 | Base.sort! 111 | Base.sort 112 | Base.sortperm 113 | Base.Sort.sortperm! 114 | Base.Sort.sortrows 115 | Base.Sort.sortcols 116 | ``` 117 | 118 | ## Order-Related Functions 119 | 120 | ```@docs 121 | Base.issorted 122 | Base.Sort.searchsorted 123 | Base.Sort.searchsortedfirst 124 | Base.Sort.searchsortedlast 125 | Base.Sort.partialsort! 126 | Base.Sort.partialsort 127 | Base.Sort.partialsortperm 128 | Base.Sort.partialsortperm! 129 | ``` 130 | 131 | ## Sorting Algorithms 132 | 133 | There are currently four sorting algorithms available in base Julia: 134 | 135 | * `InsertionSort` 136 | * `QuickSort` 137 | * `PartialQuickSort(k)` 138 | * `MergeSort` 139 | 140 | `InsertionSort` is an O(n^2) stable sorting algorithm. It is efficient for very small `n`, and 141 | is used internally by `QuickSort`. 142 | 143 | `QuickSort` is an O(n log n) sorting algorithm which is in-place, very fast, but not stable – 144 | i.e. elements which are considered equal will not remain in the same order in which they originally 145 | appeared in the array to be sorted. `QuickSort` is the default algorithm for numeric values, including 146 | integers and floats. 147 | 148 | `PartialQuickSort(k)` is similar to `QuickSort`, but the output array is only sorted up to index 149 | `k` if `k` is an integer, or in the range of `k` if `k` is an `OrdinalRange`. For example: 150 | 151 | ```julia 152 | x = rand(1:500, 100) 153 | k = 50 154 | k2 = 50:100 155 | s = sort(x; alg=QuickSort) 156 | ps = sort(x; alg=PartialQuickSort(k)) 157 | qs = sort(x; alg=PartialQuickSort(k2)) 158 | map(issorted, (s, ps, qs)) # => (true, false, false) 159 | map(x->issorted(x[1:k]), (s, ps, qs)) # => (true, true, false) 160 | map(x->issorted(x[k2]), (s, ps, qs)) # => (true, false, true) 161 | s[1:k] == ps[1:k] # => true 162 | s[k2] == qs[k2] # => true 163 | ``` 164 | 165 | `MergeSort` is an O(n log n) stable sorting algorithm but is not in-place – it requires a temporary 166 | array of half the size of the input array – and is typically not quite as fast as `QuickSort`. 167 | It is the default algorithm for non-numeric data. 168 | 169 | The default sorting algorithms are chosen on the basis that they are fast and stable, or *appear* 170 | to be so. For numeric types indeed, `QuickSort` is selected as it is faster and indistinguishable 171 | in this case from a stable sort (unless the array records its mutations in some way). The stability 172 | property comes at a non-negligible cost, so if you don't need it, you may want to explicitly specify 173 | your preferred algorithm, e.g. `sort!(v, alg=QuickSort)`. 174 | 175 | The mechanism by which Julia picks default sorting algorithms is implemented via the `Base.Sort.defalg` 176 | function. It allows a particular algorithm to be registered as the default in all sorting functions 177 | for specific arrays. For example, here are the two default methods from [`sort.jl`](https://github.com/JuliaLang/julia/blob/master/base/sort.jl): 178 | 179 | ```julia 180 | defalg(v::AbstractArray) = MergeSort 181 | defalg(v::AbstractArray{<:Number}) = QuickSort 182 | ``` 183 | 184 | As for numeric arrays, choosing a non-stable default algorithm for array types for which the notion 185 | of a stable sort is meaningless (i.e. when two values comparing equal can not be distinguished) 186 | may make sense. 187 | -------------------------------------------------------------------------------- /src/basedocs.jl: -------------------------------------------------------------------------------- 1 | import Base.BaseDocs: @kw_str 2 | 3 | """ 4 | **欢迎来到Julia $(string(VERSION)).** 完整的手册(英文)可以在这里找到 5 | 6 | https://docs.julialang.org/ 7 | 8 | 同样下面的网址也列出了很多的入门教程和课程 9 | 10 | https://julialang.org/learning/ 11 | 12 | 更多中文资料和教程,也请关注Julia中文社区 13 | 14 | https://juliacn.github.io (境内域名 juliacn.com 还在备案中) 15 | 16 | 输入 `?`, 然后输入你想要查看帮助文档的函数或者宏名称就可以查看它们的文档。例如`?cos`, 或者 `?@time` 17 | 然后按回车键即可。 18 | 19 | 退出REPL之后,重新进入将恢复英文模式。 20 | """ 21 | kw"help", kw"?", kw"julia", kw"" 22 | 23 | 24 | """ 25 | using 26 | 27 | `using Foo` 将会加载一个名为 `Foo` 的模块(module)或者一个包,然后其[`export`](@ref)的名称将可以直接使用。 28 | 不论是否被`export`,名称都可以通过点来访问(例如,输入`Foo.foo`来访问到`foo`)。查看[手册中关于模块的部分](@ref modules)以获取更多细节。 29 | """ 30 | kw"using" 31 | 32 | """ 33 | import 34 | 35 | `import Foo` 将会加载一个名为 `Foo` 的模块(module)或者一个包。 36 | `Foo`模块中的名称可以通过点来访问到(例如,输入`Foo.foo`可以获取到`foo`)。 37 | 查看[手册中关于模块的部分](@ref modules)以获取更多细节。 38 | """ 39 | kw"import" 40 | 41 | """ 42 | export 43 | 44 | `export`被用来在模块中告诉Julia哪些函数或者名字可以由用户使用。例如`export foo`将在[`using`](@ref)这个module的时候使得 45 | `foo`可以直接被访问到。查看[手册中关于模块的部分](@ref modules)以获取更多细节。 46 | """ 47 | kw"export" 48 | 49 | """ 50 | abstract type 51 | 52 | `abstract type`声明来一个不能实例化的类型,它将仅仅作为类型图中的一个节点存在,从而能够描述一系列相互关联的具体类型(concrete type): 53 | 这些具体类型都是抽象类型的子节点。抽象类型在概念上使得Julia的类型系统不仅仅是一系列对象的集合。例如: 54 | 55 | ```julia 56 | abstract type Number end 57 | abstract type Real <: Number end 58 | ``` 59 | 60 | [`Number`](@ref)没有父节点(父类型), 而 [`Real`](@ref) 是 `Number` 的一个抽象子类型。 61 | """ 62 | kw"abstract type" 63 | 64 | """ 65 | module 66 | 67 | `module` 会声明一个 `Module` 类型的实例用于描述一个独立的变量名空间。在一个模块(module)里,你可以控制 68 | 来自于其它模块的名字是否可见(通过载入,import),你也可以决定你的名字有哪些是可以公开的(通过暴露,export)。 69 | 模块使得你在在创建上层定义时无需担心命名冲突。查看[手册中关于模块的部分](@ref modules)以获取更多细节。 70 | 71 | # 例子 72 | ```julia 73 | module Foo 74 | import Base.show 75 | export MyType, foo 76 | 77 | struct MyType 78 | x 79 | end 80 | 81 | bar(x) = 2x 82 | foo(a::MyType) = bar(a.x) + 1 83 | show(io::IO, a::MyType) = print(io, "MyType \$(a.x)") 84 | end 85 | ``` 86 | """ 87 | kw"module" 88 | 89 | """ 90 | baremodule 91 | 92 | 93 | `baremodule` 将声明一个不包含`using Base`或者`eval`定义的模块。但是它将仍然载入`Core`模块。 94 | """ 95 | kw"baremodule" 96 | 97 | """ 98 | primitive type 99 | 100 | `primitive type`声明了一个其数据仅仅由一系列二进制数表示的具体类型。比较常见的例子是整数类型和浮点类型。下面是一些内置 101 | 的原始类型(primitive type): 102 | 103 | ```julia 104 | primitive type Char 32 end 105 | primitive type Bool <: Integer 8 end 106 | ``` 107 | 108 | 名称后面的数字表达了这个类型存储所需的比特数目。目前这个数字要求是8 bit的倍数。[`Bool`](@ref)类型的声明展示了一个原始类型如何 109 | 选择成为另一个类型的子类型。 110 | """ 111 | kw"primitive type" 112 | 113 | 114 | """ 115 | macro 116 | 117 | `macro`定义了一种会将生成的代码包含在最终程序体中的方法,这称之为宏。一个宏将一系列输入映射到一个表达式,然后所返回的表达式将会被 118 | 直接进行编译而不需要在运行时调用`eval`函数。宏的输入可以包括表达式,字面量,符号。例如: 119 | 120 | # 例子 121 | 122 | ```jldoctest 123 | julia> macro sayhello(name) 124 | return :( println("Hello, ", \$name, "!") ) 125 | end 126 | @sayhello (macro with 1 method) 127 | 128 | julia> @sayhello "小明" 129 | Hello, 小明! 130 | ``` 131 | """ 132 | kw"macro" 133 | 134 | """ 135 | local 136 | 137 | `local`将会定义一个新的局部变量。 138 | 139 | 查看[手册:变量作用域](@ref scope-of-variables)以获取更详细的信息。 140 | 141 | # 例子 142 | ```jldoctest 143 | julia> function foo(n) 144 | x = 0 145 | for i = 1:n 146 | local x # introduce a loop-local x 147 | x = i 148 | end 149 | x 150 | end 151 | foo (generic function with 1 method) 152 | 153 | julia> foo(10) 154 | 0 155 | ``` 156 | """ 157 | kw"local" 158 | 159 | """ 160 | global 161 | 162 | `global x`将会使得当前作用域和当前作用所包含的作用域里的`x`指向名为`x`的全局变量。 163 | 查看[手册:变量作用域](@ref scope-of-variables)以获取更多信息。 164 | 165 | # 例子 166 | ```jldoctest 167 | julia> z = 3 168 | 3 169 | 170 | julia> function foo() 171 | global z = 6 # use the z variable defined outside foo 172 | end 173 | foo (generic function with 1 method) 174 | 175 | julia> foo() 176 | 6 177 | 178 | julia> z 179 | 6 180 | ``` 181 | """ 182 | kw"global" 183 | 184 | """ 185 | let 186 | 187 | `let`会在每次被运行时声明一个新的变量绑定。这个新的变量绑定将拥有一个新的地址。这里的不同只有当 188 | 变量通过闭包生存在它们的作用域外时才会显现。`let`语法接受逗号分割的一系列赋值语句和变量名: 189 | 190 | ```julia 191 | let var1 = value1, var2, var3 = value3 192 | code 193 | end 194 | ``` 195 | 196 | 这些赋值语句是按照顺序求值的,等号右边的表达式将会首先求值,然后才绑定给左边的变量。因此这使得 `let x = x` 197 | 这样的表达式有意义,因为这两个`x`变量将具有不同的地址。 198 | """ 199 | kw"let" 200 | 201 | """ 202 | quote 203 | 204 | `quote` 会将其包含的代码扩变成一个多重的表达式对象,而无需显示调用`Expr`的构造器。这称之为引用,比如说 205 | 206 | ```julia 207 | ex = quote 208 | x = 1 209 | y = 2 210 | x + y 211 | end 212 | ``` 213 | 和其它引用方式不同的是,`:( ... )`形式的引用(被包含时)将会在表达式树里引入一个在操作表达式树时必须要考虑的`QuoteNode`元素。 214 | 而在其它场景下,`:( ... )`和 `quote .. end` 代码块是被同等对待的。 215 | """ 216 | kw"quote" 217 | 218 | 219 | """ 220 | ' 221 | 222 | 厄米算符(共轭转置),参见[`adjoint`](@ref) 223 | 224 | # 例子 225 | ```jldoctest 226 | julia> A = [1.0 -2.0im; 4.0im 2.0] 227 | 2×2 Array{Complex{Float64},2}: 228 | 1.0+0.0im -0.0-2.0im 229 | 0.0+4.0im 2.0+0.0im 230 | 231 | julia> A' 232 | 2×2 Array{Complex{Float64},2}: 233 | 1.0-0.0im 0.0-4.0im 234 | -0.0+2.0im 2.0-0.0im 235 | ``` 236 | """ 237 | kw"'" 238 | 239 | 240 | """ 241 | .' 242 | 243 | 转置算符,参见[`transpose`](@ref) 244 | 245 | # 例子 246 | ```jldoctest 247 | julia> A = [1.0 -2.0im; 4.0im 2.0] 248 | 2×2 Array{Complex{Float64},2}: 249 | 1.0+0.0im -0.0-2.0im 250 | 0.0+4.0im 2.0+0.0im 251 | 252 | julia> A.' 253 | 2×2 Array{Complex{Float64},2}: 254 | 1.0+0.0im 0.0+4.0im 255 | -0.0-2.0im 2.0+0.0im 256 | ``` 257 | """ 258 | kw".'" 259 | 260 | 261 | """ 262 | const 263 | 264 | `const`被用来声明常数全局变量。在大部分(尤其是性能敏感的代码)全局变量应当被声明为常数。 265 | 266 | ```julia 267 | const x = 5 268 | ``` 269 | 270 | 可以使用单个`const`声明多个常数变量。 271 | ```julia 272 | const y, z = 7, 11 273 | ``` 274 | 275 | 注意`const`只会作用于一个`=`操作,因此 `const x = y = 1` 声明了 `x` 是常数,而 `y` 不是。在另一方面, 276 | `const x = const y = 1`声明了`x`和`y`都是常数。 277 | 278 | 注意 “常数性质” 并不会强制容器内部变成常数,所以如果`x`是一个数组或者字典(举例来讲)你仍然可以给它们添加 279 | 或者删除元素。 280 | 281 | 严格来讲,你甚至可以重新定义 `const` (常数)变量,尽管这将会让编译器产生一个警告。唯一严格的要求是这个变量的 282 | **类型**不能改变,这也是为什么常数变量会比一般的全局变量更快的原因。 283 | """ 284 | kw"const" 285 | 286 | """ 287 | function 288 | 289 | 函数由`function`关键词定义: 290 | 291 | ```julia 292 | function add(a, b) 293 | return a + b 294 | end 295 | ``` 296 | 297 | 或者是更短的形式: 298 | 299 | ```julia 300 | add(a, b) = a + b 301 | ``` 302 | 303 | [`return`](@ref)关键词的使用方法和其它语言完全一样,但是常常是不使用的。一个没有显示声明`return`的函数将返回函数体最后一个表达式。 304 | """ 305 | kw"function" 306 | -------------------------------------------------------------------------------- /docs/src/base/collections.md: -------------------------------------------------------------------------------- 1 | # Collections and Data Structures 2 | 3 | ## [Iteration](@id lib-collections-iteration) 4 | 5 | Sequential iteration is implemented by the [`iterate`](@ref) function. 6 | The general `for` loop: 7 | 8 | ```julia 9 | for i in iter # or "for i = iter" 10 | # body 11 | end 12 | ``` 13 | 14 | is translated into: 15 | 16 | ```julia 17 | next = iterate(iter) 18 | while next !== nothing 19 | (i, state) = next 20 | # body 21 | next = iterate(iter, state) 22 | end 23 | ``` 24 | 25 | The `state` object may be anything, and should be chosen appropriately for each iterable type. 26 | See the [manual section on the iteration interface](@ref man-interface-iteration) for more details about defining a custom 27 | iterable type. 28 | 29 | ```@docs 30 | Base.iterate 31 | Base.IteratorSize 32 | Base.IteratorEltype 33 | ``` 34 | 35 | Fully implemented by: 36 | 37 | * [`AbstractRange`](@ref) 38 | * [`UnitRange`](@ref) 39 | * `Tuple` 40 | * `Number` 41 | * [`AbstractArray`](@ref) 42 | * [`BitSet`](@ref) 43 | * [`IdDict`](@ref) 44 | * [`Dict`](@ref) 45 | * [`WeakKeyDict`](@ref) 46 | * `EachLine` 47 | * `AbstractString` 48 | * [`Set`](@ref) 49 | * [`Pair`](@ref) 50 | * [`NamedTuple`](@ref) 51 | 52 | ## Constructors and Types 53 | 54 | ```@docs 55 | Base.AbstractRange 56 | Base.OrdinalRange 57 | Base.AbstractUnitRange 58 | Base.StepRange 59 | Base.UnitRange 60 | Base.LinRange 61 | ``` 62 | 63 | ## General Collections 64 | 65 | ```@docs 66 | Base.isempty 67 | Base.empty! 68 | Base.length 69 | ``` 70 | 71 | Fully implemented by: 72 | 73 | * [`AbstractRange`](@ref) 74 | * [`UnitRange`](@ref) 75 | * `Tuple` 76 | * `Number` 77 | * [`AbstractArray`](@ref) 78 | * [`BitSet`](@ref) 79 | * [`IdDict`](@ref) 80 | * [`Dict`](@ref) 81 | * [`WeakKeyDict`](@ref) 82 | * `AbstractString` 83 | * [`Set`](@ref) 84 | * [`NamedTuple`](@ref) 85 | 86 | ## Iterable Collections 87 | 88 | ```@docs 89 | Base.in 90 | Base.:∉ 91 | Base.eltype 92 | Base.indexin 93 | Base.unique 94 | Base.unique! 95 | Base.allunique 96 | Base.reduce(::Any, ::Any) 97 | Base.foldl(::Any, ::Any) 98 | Base.foldr(::Any, ::Any) 99 | Base.maximum 100 | Base.maximum! 101 | Base.minimum 102 | Base.minimum! 103 | Base.extrema 104 | Base.argmax 105 | Base.argmin 106 | Base.findmax 107 | Base.findmin 108 | Base.findmax! 109 | Base.findmin! 110 | Base.sum 111 | Base.sum! 112 | Base.prod 113 | Base.prod! 114 | Base.any(::Any) 115 | Base.any(::AbstractArray, ::Any) 116 | Base.any! 117 | Base.all(::Any) 118 | Base.all(::AbstractArray, ::Any) 119 | Base.all! 120 | Base.count 121 | Base.any(::Any, ::Any) 122 | Base.all(::Any, ::Any) 123 | Base.foreach 124 | Base.map 125 | Base.map! 126 | Base.mapreduce(::Any, ::Any, ::Any) 127 | Base.mapfoldl(::Any, ::Any, ::Any) 128 | Base.mapfoldr(::Any, ::Any, ::Any) 129 | Base.first 130 | Base.last 131 | Base.step 132 | Base.collect(::Any) 133 | Base.collect(::Type, ::Any) 134 | Base.filter 135 | Base.filter! 136 | Base.replace(::Any, ::Pair...) 137 | Base.replace(::Base.Callable, ::Any, ::Any) 138 | Base.replace(::Base.Callable, ::Any) 139 | Base.replace! 140 | ``` 141 | 142 | ## Indexable Collections 143 | 144 | ```@docs 145 | Base.getindex 146 | Base.setindex! 147 | Base.firstindex 148 | Base.lastindex 149 | ``` 150 | 151 | Fully implemented by: 152 | 153 | * [`Array`](@ref) 154 | * [`BitArray`](@ref) 155 | * [`AbstractArray`](@ref) 156 | * `SubArray` 157 | 158 | Partially implemented by: 159 | 160 | * [`AbstractRange`](@ref) 161 | * [`UnitRange`](@ref) 162 | * `Tuple` 163 | * `AbstractString` 164 | * [`Dict`](@ref) 165 | * [`IdDict`](@ref) 166 | * [`WeakKeyDict`](@ref) 167 | * [`NamedTuple`](@ref) 168 | 169 | ## Dictionaries 170 | 171 | [`Dict`](@ref) is the standard dictionary. Its implementation uses [`hash`](@ref) 172 | as the hashing function for the key, and [`isequal`](@ref) to determine equality. Define these 173 | two functions for custom types to override how they are stored in a hash table. 174 | 175 | [`IdDict`](@ref) is a special hash table where the keys are always object identities. 176 | 177 | [`WeakKeyDict`](@ref) is a hash table implementation where the keys are weak references to objects, and 178 | thus may be garbage collected even when referenced in a hash table. 179 | 180 | [`Dict`](@ref)s can be created by passing pair objects constructed with `=>` to a [`Dict`](@ref) 181 | constructor: `Dict("A"=>1, "B"=>2)`. This call will attempt to infer type information from the 182 | keys and values (i.e. this example creates a `Dict{String, Int64}`). To explicitly specify types 183 | use the syntax `Dict{KeyType,ValueType}(...)`. For example, `Dict{String,Int32}("A"=>1, "B"=>2)`. 184 | 185 | Dictionaries may also be created with generators. For example, `Dict(i => f(i) for i = 1:10)`. 186 | 187 | Given a dictionary `D`, the syntax `D[x]` returns the value of key `x` (if it exists) or throws 188 | an error, and `D[x] = y` stores the key-value pair `x => y` in `D` (replacing any existing value 189 | for the key `x`). Multiple arguments to `D[...]` are converted to tuples; for example, the syntax 190 | `D[x,y]` is equivalent to `D[(x,y)]`, i.e. it refers to the value keyed by the tuple `(x,y)`. 191 | 192 | ```@docs 193 | Base.Dict 194 | Base.IdDict 195 | Base.WeakKeyDict 196 | Base.ImmutableDict 197 | Base.haskey 198 | Base.get(::Any, ::Any, ::Any) 199 | Base.get 200 | Base.get!(::Any, ::Any, ::Any) 201 | Base.get!(::Function, ::Any, ::Any) 202 | Base.getkey 203 | Base.delete! 204 | Base.pop!(::Any, ::Any, ::Any) 205 | Base.keys 206 | Base.values 207 | Base.pairs 208 | Base.merge 209 | Base.merge!(::AbstractDict, ::AbstractDict...) 210 | Base.merge!(::Function, ::AbstractDict, ::AbstractDict...) 211 | Base.sizehint! 212 | Base.keytype 213 | Base.valtype 214 | ``` 215 | 216 | Fully implemented by: 217 | 218 | * [`IdDict`](@ref) 219 | * [`Dict`](@ref) 220 | * [`WeakKeyDict`](@ref) 221 | 222 | Partially implemented by: 223 | 224 | * [`BitSet`](@ref) 225 | * [`Set`](@ref) 226 | * [`EnvDict`](@ref Base.EnvDict) 227 | * [`Array`](@ref) 228 | * [`BitArray`](@ref) 229 | * [`ImmutableDict`](@ref Base.ImmutableDict) 230 | * [`Iterators.Pairs`](@ref) 231 | 232 | ## Set-Like Collections 233 | 234 | ```@docs 235 | Base.Set 236 | Base.BitSet 237 | Base.union 238 | Base.union! 239 | Base.intersect 240 | Base.setdiff 241 | Base.setdiff! 242 | Base.symdiff 243 | Base.symdiff! 244 | Base.intersect! 245 | Base.issubset 246 | Base.:⊈ 247 | Base.:⊊ 248 | Base.issetequal 249 | ``` 250 | 251 | Fully implemented by: 252 | 253 | * [`BitSet`](@ref) 254 | * [`Set`](@ref) 255 | 256 | Partially implemented by: 257 | 258 | * [`Array`](@ref) 259 | 260 | ## Dequeues 261 | 262 | ```@docs 263 | Base.push! 264 | Base.pop! 265 | Base.pushfirst! 266 | Base.popfirst! 267 | Base.insert! 268 | Base.deleteat! 269 | Base.splice! 270 | Base.resize! 271 | Base.append! 272 | Base.prepend! 273 | ``` 274 | 275 | Fully implemented by: 276 | 277 | * `Vector` (a.k.a. 1-dimensional [`Array`](@ref)) 278 | * `BitVector` (a.k.a. 1-dimensional [`BitArray`](@ref)) 279 | 280 | ## Utility Collections 281 | 282 | ```@docs 283 | Base.Pair 284 | Iterators.Pairs 285 | ``` 286 | -------------------------------------------------------------------------------- /docs/src/manual/variables.md: -------------------------------------------------------------------------------- 1 | # 变量 2 | 3 | ```@raw html 4 | 5 | ``` 6 | 7 | Julia 中,变量(Variable)即是关联(或绑定)到一个值的名字。当你想存下一个值(比如从某些数学运算后得到的)以备后用时,变量就显得非常有用。例如: 8 | 9 | ```@raw html 10 | 12 | ``` 13 | 14 | ```julia-repl 15 | # Assign the value 10 to the variable x 16 | julia> x = 10 17 | 10 18 | 19 | # Doing math with x's value 20 | julia> x + 1 21 | 11 22 | 23 | # Reassign x's value 24 | julia> x = 1 + 1 25 | 2 26 | 27 | # You can assign values of other types, like strings of text 28 | julia> x = "Hello World!" 29 | "Hello World!" 30 | ``` 31 | 32 | Julia 为变量命名提供了一个极其灵活的系统。变量名区分大小写,并且没有语义上的意义(语言不会因为变量的名字区别而区别对待它们)。 33 | 34 | ```@raw html 35 | 38 | ``` 39 | 40 | ```jldoctest 41 | julia> x = 1.0 42 | 1.0 43 | 44 | julia> y = -3 45 | -3 46 | 47 | julia> Z = "My string" 48 | "My string" 49 | 50 | julia> customary_phrase = "Hello world!" 51 | "Hello world!" 52 | 53 | julia> UniversalDeclarationOfHumanRightsStart = "人人生而自由,在尊严和权利上一律平等。" 54 | "人人生而自由,在尊严和权利上一律平等。" 55 | ``` 56 | 57 | 也可以使用 Unicode 字符(UTF-8 编码)来命名: 58 | 59 | ```@raw html 60 | 61 | ``` 62 | 63 | ```jldoctest 64 | julia> δ = 0.00001 65 | 1.0e-5 66 | 67 | julia> 안녕하세요 = "Hello" 68 | "Hello" 69 | ``` 70 | 71 | 在 Julia 的 REPL 以及一些其它的 Julia 编辑环境中,很多 Unicode 的数学符号可以使用反斜杠加 LaTeX 符号名并跟上一个 tab 打出。例如,想输入变量名 `δ` 的话,可以输入 `\delta`-*tab*。你甚至可以用 `\alpha`-*tab*-`\hat`-*tab*-`\_2`-*tab* 来输入 `α̂₂` 这样复杂的名字。如果你在某个地方(比如别人的代码里)看到一个不知道怎么输入的符号,REPL 的帮助功能会告诉你:只需要输入 `?` 然后粘贴上那个符号即可。 72 | 73 | ```@raw html 74 | 80 | ``` 81 | 82 | Julia 甚至允许你在需要的时候重新定义那些内建常量和函数(虽然为了避免潜在的混乱,这是不被推荐的): 83 | 84 | ```@raw html 85 | 87 | ``` 88 | 89 | ```jldoctest 90 | julia> pi = 3 91 | 3 92 | 93 | julia> pi 94 | 3 95 | 96 | julia> sqrt = 4 97 | 4 98 | ``` 99 | 100 | 然而,如果试图重新定义一个已经在使用中的内建常量或函数,Julia 会报错: 101 | 102 | ```@raw html 103 | 105 | ``` 106 | 107 | ```jldoctest 108 | julia> pi 109 | π = 3.1415926535897... 110 | 111 | julia> pi = 3 112 | ERROR: cannot assign variable MathConstants.pi from module Main 113 | 114 | julia> sqrt(100) 115 | 10.0 116 | 117 | julia> sqrt = 4 118 | ERROR: cannot assign variable Base.sqrt from module Main 119 | ``` 120 | 121 | ## 可用的变量名 122 | ```@raw html 123 | 124 | ``` 125 | 126 | 变量名的第一位必须以下字符: 127 | * 字母(A-Z 或者 a-z)或下划线(_) 128 | * 或编码大于 00A0 的 Unicode 字符的一个子集。具体来说指的是,[Unicode 字符分类](http://www.fileformat.info/info/unicode/category/index.htm)中的 129 | * Lu/Ll/Lt/Lm/Lo/Nl(字母) 130 | * Sc/So(货币及其他符号) 131 | * 一些其它像字母的符号(比如,Sm 数学符号的一个子集) 132 | 133 | 后续的字符可以包含 ! 和数字(0-9 和其它处于 Nd/No 分类中的字符),以及其它 Unicode 字符:变音和其它修饰符号(Mn/Mc/Me/Sk 分类),一些连接标点(Pc 分类),角分符号和一些其他字符。 134 | ```@raw html 135 | 136 | 143 | ``` 144 | 145 | 像 `+` 这样的运算符也是合法的标识符,但会被特殊地解析。在一些上下文中,运算符可以就像变量一样被使用。比如说,`(+)` 指的是加法函数,且 `(+) = f` 会把它重新赋值。大多数表示中缀运算符的 Unicode 字符(在 Sm 分类中的),比如说 `⊕`,都会被解析成中缀运算符,且可供用户定义的方法使用(比如说,可以用 `const ⊗ = kron` 来定义 `⊗` 为一个中缀的克罗内克积)。运算符也可以放在一些修饰符、角分符号和上下标之前,比如说 `+̂ₐ″` 会被解析成一个和 `+` 同样优先级的中缀运算符。 146 | 147 | ```@raw html 148 | 155 | ``` 156 | 157 | 内建语句的名字是唯一明确被禁止的变量名: 158 | 159 | ```@raw html 160 | 161 | ``` 162 | 163 | ```julia-repl 164 | julia> else = false 165 | ERROR: syntax: unexpected "else" 166 | 167 | julia> try = "No" 168 | ERROR: syntax: unexpected "=" 169 | ``` 170 | 171 | 有一些 Unicode 字符作为标识符会被认为是等价的。输入 Unicode 组合字符(比如重音)的不同方式也被看作是等价的(具体来说,Julia 标识符是 NFC-正规化的)。Unicode 字符 `ɛ` (U+025B: Latin small letter open e) 和 `µ` (U+00B5: micro sign) 会被视为与相应的希腊字母等价,因为前者在一些输入方式中很容易访问到。 172 | 173 | ```@raw html 174 | 180 | ``` 181 | 182 | ## 命名规范 183 | 184 | ```@raw html 185 | 186 | 187 | ``` 188 | 189 | 尽管 Julia 对命名本身只有很少的限制,但遵循下列规范是很有用的: 190 | 191 | ```@raw html 192 | 193 | 195 | ``` 196 | 197 | * 变量名使用小写字母。 198 | * 单词分隔符可以使用下划线(`'_'`),但除非名字很难阅读否则并不鼓励使用下划线。 199 | * `Type` 和 `Module` 的名字都使用大写字母开头,且单词的分隔使用大写驼峰命名法而不是下划线。 200 | * `function` 和 `macro` 的名字使用小写字母,并不含下划线。 201 | * 会写入自身参数的函数名使用 `!` 作为结尾。这样的函数有时被称为“变异(mutating)”或是“原地(in-place)”函数,因为调用它们除了会返回一个值之外,参数还会产生变化。 202 | 203 | ```@raw html 204 | 213 | ``` 214 | 215 | 关于命名规范的更多信息请参考[代码风格指南](@ref)。 216 | 217 | ```@raw html 218 | 219 | 220 | ``` 221 | -------------------------------------------------------------------------------- /docs/src/base/base.md: -------------------------------------------------------------------------------- 1 | 2 | ```@raw html 3 | 4 | ``` 5 | # 重要组件 6 | 7 | ```@raw html 8 | 9 | ``` 10 | 11 | ## 简介 12 | 13 | ```@raw html 14 | 18 | ``` 19 | 20 | Julia的基础模块不仅包含了一系列为科学计算和数值计算打造的函数和宏,也包含了广泛的 21 | 为一般目的编程所需的基础设置。额外的功能可以通过增加包来获得。函数被组织为如下的主题。 22 | 23 | ```@raw html 24 | 31 | ``` 32 | 33 | 一些一般的注记: 34 | 35 | * 如需使用模块里的函数,请通过 `import Module` 来载入模块,然后使用 `Module.fn(x)` 来使用这个函数。 36 | * 或者,你也可以通过 `using Module` 来载入所有被 `Module` 暴露的函数到当前的命名空间中 37 | * 按照约定,函数名称以感叹号(`!`)结尾的将会修改它们的输入,一些函数会有修改(副作用)和不修改两种版本 38 | 39 | ```@raw html 40 | 41 | ``` 42 | 43 | ## 随便看看 44 | 45 | ```@docs 46 | Base.exit 47 | Base.atexit 48 | Base.isinteractive 49 | Base.summarysize 50 | Base.require 51 | Base.compilecache 52 | Base.__precompile__ 53 | Base.include 54 | Base.MainInclude.include 55 | Base.include_string 56 | Base.include_dependency 57 | Base.which(::Any, ::Any) 58 | Base.methods 59 | Base.@show 60 | ans 61 | ``` 62 | 63 | ```@raw html 64 | 65 | ``` 66 | 67 | ## 关键词 68 | 69 | ```@docs 70 | module 71 | export 72 | import 73 | using 74 | baremodule 75 | function 76 | macro 77 | return 78 | do 79 | begin 80 | end 81 | let 82 | if 83 | for 84 | while 85 | break 86 | continue 87 | try 88 | finally 89 | quote 90 | local 91 | global 92 | const 93 | struct 94 | mutable struct 95 | abstract type 96 | primitive type 97 | ... 98 | ; 99 | ``` 100 | 101 | ```@raw html 102 | 103 | ``` 104 | ## 基础库 105 | 106 | ```@docs 107 | Base.Base 108 | Base.Broadcast 109 | Base.Docs 110 | Base.Iterators 111 | Base.Libc 112 | Base.Meta 113 | Base.StackTraces 114 | Base.Sys 115 | Base.Threads 116 | Base.GC 117 | ``` 118 | 119 | ```@raw html 120 | 121 | ``` 122 | ## 所有的对象 123 | 124 | ```@docs 125 | Core.:(===) 126 | Core.isa 127 | Base.isequal 128 | Base.isless 129 | Base.ifelse 130 | Core.typeassert 131 | Core.typeof 132 | Core.tuple 133 | Base.ntuple 134 | Base.objectid 135 | Base.hash 136 | Base.finalizer 137 | Base.finalize 138 | Base.copy 139 | Base.deepcopy 140 | Base.getproperty 141 | Base.setproperty! 142 | Base.propertynames 143 | Core.getfield 144 | Core.setfield! 145 | Core.isdefined 146 | Base.@isdefined 147 | Base.convert 148 | Base.promote 149 | Base.oftype 150 | Base.widen 151 | Base.identity 152 | ``` 153 | 154 | ```@raw html 155 | 156 | ``` 157 | ## 类型的性质 158 | 159 | ```@raw html 160 | 161 | ``` 162 | ### 类型之间的关系 163 | 164 | ```@docs 165 | Base.supertype 166 | Core.:(<:) 167 | Base.:(>:) 168 | Base.typejoin 169 | Base.typeintersect 170 | Base.promote_type 171 | Base.promote_rule 172 | Base.isdispatchtuple 173 | ``` 174 | 175 | ```@raw html 176 | 177 | ``` 178 | ### 声明的结构 179 | 180 | ```@docs 181 | Base.isimmutable 182 | Base.isabstracttype 183 | Base.isprimitivetype 184 | Base.isstructtype 185 | Base.nameof(::DataType) 186 | Base.fieldnames 187 | Base.fieldname 188 | ``` 189 | 190 | ```@raw html 191 | 192 | ``` 193 | ### 内存布局 194 | 195 | ```@docs 196 | Base.sizeof(::Type) 197 | Base.isconcretetype 198 | Base.isbits 199 | Base.isbitstype 200 | Core.fieldtype 201 | Base.fieldcount 202 | Base.fieldoffset 203 | Base.datatype_alignment 204 | Base.datatype_haspadding 205 | Base.datatype_pointerfree 206 | ``` 207 | 208 | ```@raw html 209 | 210 | ``` 211 | ### 特殊值 212 | 213 | ```@docs 214 | Base.typemin 215 | Base.typemax 216 | Base.realmin 217 | Base.realmax 218 | Base.maxintfloat 219 | Base.eps(::Type{<:AbstractFloat}) 220 | Base.eps(::AbstractFloat) 221 | Base.instances 222 | ``` 223 | 224 | ```@raw html 225 | 226 | ``` 227 | ## 特别的类型 228 | 229 | ```@docs 230 | Core.Any 231 | Core.Union 232 | Union{} 233 | Core.UnionAll 234 | Core.Tuple 235 | Core.NamedTuple 236 | Base.Val 237 | Core.Vararg 238 | Core.Nothing 239 | Base.Some 240 | Base.something 241 | Base.Enums.@enum 242 | ``` 243 | 244 | ```@raw html 245 | 246 | ``` 247 | ## 一般的函数 248 | 249 | ```@docs 250 | Core.Function 251 | Base.hasmethod 252 | Core.applicable 253 | Core.invoke 254 | Base.invokelatest 255 | new 256 | Base.:(|>) 257 | Base.:(∘) 258 | ``` 259 | 260 | ```@raw html 261 | 262 | ``` 263 | ## 句法 264 | 265 | ```@docs 266 | Core.eval 267 | Base.MainInclude.eval 268 | Base.@eval 269 | Base.evalfile 270 | Base.esc 271 | Base.@inbounds 272 | Base.@boundscheck 273 | Base.@inline 274 | Base.@noinline 275 | Base.@nospecialize 276 | Base.gensym 277 | Base.@gensym 278 | Base.@goto 279 | Base.@label 280 | Base.@simd 281 | Base.@polly 282 | ``` 283 | 284 | ```@raw html 285 | 286 | ``` 287 | ## 缺失值 288 | 289 | ```@docs 290 | Base.Missing 291 | Base.missing 292 | Base.coalesce 293 | Base.ismissing 294 | Base.skipmissing 295 | ``` 296 | 297 | ```@raw html 298 | 299 | ``` 300 | ## 系统 301 | 302 | ```@docs 303 | Base.run 304 | Base.devnull 305 | Base.success 306 | Base.process_running 307 | Base.process_exited 308 | Base.kill(::Base.Process, ::Integer) 309 | Base.Sys.set_process_title 310 | Base.Sys.get_process_title 311 | Base.readandwrite 312 | Base.ignorestatus 313 | Base.detach 314 | Base.Cmd 315 | Base.setenv 316 | Base.withenv 317 | Base.pipeline(::Any, ::Any, ::Any, ::Any...) 318 | Base.pipeline(::Base.AbstractCmd) 319 | Base.Libc.gethostname 320 | Base.Libc.getpid 321 | Base.Libc.time() 322 | Base.time_ns 323 | Base.@time 324 | Base.@timev 325 | Base.@timed 326 | Base.@elapsed 327 | Base.@allocated 328 | Base.EnvDict 329 | Base.ENV 330 | Base.Sys.isunix 331 | Base.Sys.isapple 332 | Base.Sys.islinux 333 | Base.Sys.isbsd 334 | Base.Sys.iswindows 335 | Base.Sys.windows_version 336 | Base.@static 337 | ``` 338 | 339 | ```@raw html 340 | 341 | ``` 342 | ## 版本 343 | 344 | ```@docs 345 | Base.VersionNumber 346 | Base.@v_str 347 | ``` 348 | 349 | ```@raw html 350 | 351 | ``` 352 | ## 错误 353 | 354 | ```@docs 355 | Base.error 356 | Core.throw 357 | Base.rethrow 358 | Base.backtrace 359 | Base.catch_backtrace 360 | Base.@assert 361 | Base.ArgumentError 362 | Base.AssertionError 363 | Core.BoundsError 364 | Base.CompositeException 365 | Base.DimensionMismatch 366 | Core.DivideError 367 | Core.DomainError 368 | Base.EOFError 369 | Core.ErrorException 370 | Core.InexactError 371 | Core.InterruptException 372 | Base.KeyError 373 | Base.LoadError 374 | Base.MethodError 375 | Base.MissingException 376 | Core.OutOfMemoryError 377 | Core.ReadOnlyMemoryError 378 | Core.OverflowError 379 | Core.StackOverflowError 380 | Base.SystemError 381 | Core.TypeError 382 | Core.UndefKeywordError 383 | Core.UndefRefError 384 | Core.UndefVarError 385 | Base.StringIndexError 386 | Base.InitError 387 | Base.retry 388 | Base.ExponentialBackOff 389 | ``` 390 | 391 | ```@raw html 392 | 393 | ``` 394 | ## 事件 395 | 396 | ```@docs 397 | Base.Timer(::Function, ::Real) 398 | Base.Timer 399 | Base.AsyncCondition 400 | Base.AsyncCondition(::Function) 401 | ``` 402 | 403 | ```@raw html 404 | 405 | ``` 406 | ## 反射 407 | 408 | ```@docs 409 | Base.nameof(::Module) 410 | Base.parentmodule 411 | Base.moduleroot 412 | Base.@__MODULE__ 413 | Base.fullname 414 | Base.names 415 | Core.nfields 416 | Base.isconst 417 | Base.nameof(::Function) 418 | Base.functionloc(::Any, ::Any) 419 | Base.functionloc(::Method) 420 | ``` 421 | 422 | ```@raw html 423 | 424 | ``` 425 | 426 | ## 内部构件 427 | 428 | ```@docs 429 | Base.GC.gc 430 | Base.GC.enable 431 | Base.GC.@preserve 432 | Meta.lower 433 | Meta.@lower 434 | Meta.parse(::AbstractString, ::Int) 435 | Meta.parse(::AbstractString) 436 | Meta.ParseError 437 | Base.macroexpand 438 | Base.@macroexpand 439 | Base.@macroexpand1 440 | Base.code_lowered 441 | Base.code_typed 442 | Base.precompile 443 | ``` 444 | -------------------------------------------------------------------------------- /docs/src/manual/getting-started.md: -------------------------------------------------------------------------------- 1 | ```@raw html 2 | 3 | ``` 4 | 5 | # [起步](@id man-getting-started) 6 | 7 | ```@raw html 8 | 10 | ``` 11 | 12 | 不管是用编译好的程序,还是自己从源码编译,安装 Julia 都是一件很简单的事情。按照 [https://julialang.org/downloads/](https://julialang.org/downloads/) 的提示就可以轻松下载并安装 Julia。 13 | 14 | ```@raw html 15 | 18 | ``` 19 | 20 | 启动一个交互式会话(也被叫做 REPL)是学习和尝试 Julia 最简单的方法。双击 Julia 的可执行文件或是从命令行运行 `julia` 就可以启动: 21 | 22 | ```@eval 23 | io = IOBuffer() 24 | Base.banner(io) 25 | banner = String(take!(io)) 26 | import Markdown 27 | Markdown.parse("```\n\$ julia\n\n$(banner)\njulia> 1 + 2\n3\n\njulia> ans\n3\n```") 28 | ``` 29 | 30 | ```@raw html 31 | 38 | ``` 39 | 40 | 输入 `^D` (`Ctrl` 和 `d` 两键同时按)或 `quit()` 以退出交互式会话。在交互式模式中,`julia` 会显示一个大标题并提示用户输入。一旦用户输入了一个完整的表达式,例如 `1 + 2`,然后敲回车,交互式会话就会对表达式进行求值并显示出来。如果一个输入交互式会话中的表达式以分号结尾,求得的值将不会被显示。变量 `ans` 被绑定到上一个被求值的表达式的结果,不管有没有被显示。注意 `ans` 变量只适用于交互式会话中,不适用于其它方法运行的 Julia。 41 | 42 | ```@raw html 43 | 44 | ``` 45 | 46 | 如果想运行写在源文件 `file.jl` 中的表达式,只需输入 `include("file.jl")`。 47 | 48 | ```@raw html 49 | 51 | ``` 52 | 53 | 如果想非交互式地执行文件中的代码,可以把文件名作为 `julia` 命令的第一个参数: 54 | 55 | ``` 56 | $ julia script.jl arg1 arg2... 57 | ``` 58 | 59 | ```@raw html 60 | 66 | ``` 67 | 68 | 如这个例子所示,`julia` 后跟着的命令行参数会被作为程序 `script.jl` 的命令行参数。这些参数使用全局常量 `ARGS` 来传递,脚本自身的名字会以全局常量 `PROGRAM_FILE` 传入。注意当脚本以命令行里的 `-e` 选项输入时,`ARGS` 也会被设定(见下面的 `julia` 帮助输出)但是 `PROGRAM_FILE` 会是空的。比如说,如果想把输入给一个脚本的参数给显示出来,你可以这么写: 69 | 70 | ``` 71 | $ julia -e 'println(PROGRAM_FILE); for x in ARGS; println(x); end' foo bar 72 | 73 | foo 74 | bar 75 | ``` 76 | 77 | ```@raw html 78 | 79 | ``` 80 | 81 | 或者你可以把代码写到一个脚本文件中再执行它: 82 | 83 | ``` 84 | $ echo 'println(PROGRAM_FILE); for x in ARGS; println(x); end' > script.jl 85 | $ julia script.jl foo bar 86 | script.jl 87 | foo 88 | bar 89 | ``` 90 | 91 | ```@raw html 92 | 93 | ``` 94 | 95 | 可以使用 `--` 分隔符来将传给脚本文件和 Julia 本身的命令行参数分开: 96 | 97 | ``` 98 | $ julia --color=yes -O -- foo.jl arg1 arg2.. 99 | ``` 100 | 101 | ```@raw html 102 | 110 | ``` 111 | 112 | 使用选项 `-p` 或者 `--machine-file` 可以在并行模式下启动 Julia。`-p n` 会启动额外的 `n` 个 worker,`--machine-file file` 会为 `file` 文件中的每一行启动一个 worker。被定义在 `file` 中的机器必须能够通过一个不需要密码的 `ssh` 登陆访问到,且 Julia 的安装位置需要和当前主机相同。定义机器的格式为 `[count*][user@]host[:port] [bind_addr[:port]]`。`user` 默认值是当前用户,`port` 默认值是标准 ssh 端口。`count` 是在这个节点上的 worker 的数量,默认是 1。可选的 `bind-to bind_addr[:port]` 指定了其它 worker 访问当前 worker 应当使用的 IP 地址与端口。 113 | 114 | ```@raw html 115 | 117 | ``` 118 | 119 | 如果你有一些代码,想让 Julia 每次启动都会自动执行,可以把它们放在 `~/.juliarc.jl` 中: 120 | 121 | ``` 122 | $ echo 'println("Greetings! 你好! 안녕하세요?")' > ~/.julia/config/startup.jl 123 | $ julia 124 | Greetings! 你好! 안녕하세요? 125 | 126 | ... 127 | ``` 128 | 129 | ```@raw html 130 | 132 | ``` 133 | 134 | 还有很多种运行 Julia 代码和提供选项的方法,和 `perl` 和 `ruby` 之类的程序中可用的方法类似: 135 | 136 | ``` 137 | julia [switches] -- [programfile] [args...] 138 | ``` 139 | 140 | 141 | |Switch |Description| 142 | |:--- |:---| 143 | |`-v`, `--version` |Display version information| 144 | |`-h`, `--help` |Print this message| 145 | |`-J`, `--sysimage ` |Start up with the given system image file| 146 | |`-H`, `--home ` |Set location of `julia` executable| 147 | |`--startup-file={yes\|no}` |Load `~/.julia/config/startup.jl`| 148 | |`--handle-signals={yes\|no}` |Enable or disable Julia's default signal handlers| 149 | |`--sysimage-native-code={yes\|no}` |Use native code from system image if available| 150 | |`--compiled-modules={yes\|no}` |Enable or disable incremental precompilation of modules| 151 | |`-e`, `--eval ` |Evaluate ``| 152 | |`-E`, `--print ` |Evaluate `` and display the result| 153 | |`-L`, `--load ` |Load `` immediately on all processors| 154 | |`-p`, `--procs {N\|auto`} |Integer value N launches N additional local worker processes; `auto` launches as many workers as the number of local CPU threads (logical cores)| 155 | |`--machine-file ` |Run processes on hosts listed in ``| 156 | |`-i` |Interactive mode; REPL runs and `isinteractive()` is true| 157 | |`-q`, `--quiet` |Quiet startup: no banner, suppress REPL warnings| 158 | |`--banner={yes\|no\|auto}` |Enable or disable startup banner| 159 | |`--color={yes\|no\|auto}` |Enable or disable color text| 160 | |`--history-file={yes\|no}` |Load or save history| 161 | |`--depwarn={yes\|no\|error}` |Enable or disable syntax and method deprecation warnings (`error` turns warnings into errors)| 162 | |`--warn-overwrite={yes\|no}` |Enable or disable method overwrite warnings| 163 | |`-C`, `--cpu-target ` |Limit usage of cpu features up to ; set to `help` to see the available options| 164 | |`-O`, `--optimize={0,1,2,3}` |Set the optimization level (default level is 2 if unspecified or 3 if used without a level)| 165 | |`-g`, `-g ` |Enable / Set the level of debug info generation (default level is 1 if unspecified or 2 if used without a level)| 166 | |`--inline={yes\|no}` |Control whether inlining is permitted, including overriding `@inline` declarations| 167 | |`--check-bounds={yes\|no}` |Emit bounds checks always or never (ignoring declarations)| 168 | |`--math-mode={ieee,fast}` |Disallow or enable unsafe floating point optimizations (overrides @fastmath declaration)| 169 | |`--code-coverage={none\|user\|all}` |Count executions of source lines| 170 | |`--code-coverage` |equivalent to `--code-coverage=user`| 171 | |`--track-allocation={none\|user\|all}` |Count bytes allocated by each source line| 172 | |`--track-allocation` |equivalent to `--track-allocation=user`| 173 | 174 | ```@raw html 175 | 176 | ``` 177 | 178 | ## 资源 179 | 180 | 除了本手册以外,官方网站上还有很多其它可以帮助新用户学习 Julia 的资源(英文),这里是一个学习资源的列表:[learning](https://julialang.org/learning/) 181 | -------------------------------------------------------------------------------- /docs/src/index.md: -------------------------------------------------------------------------------- 1 | # Julia 0.7 中文文档 2 | 3 | ```@raw html 4 | 5 | ``` 6 | 7 | 欢迎来到Julia 0.7中文文档。 8 | 9 | ```@raw html 10 | 11 | 12 | 13 | ``` 14 | 15 | ```@raw html 16 | 17 | ``` 18 | 19 | ### [简介](@id man-introduction) 20 | 21 | ```@raw html 22 | 30 | ``` 31 | 32 | 科学计算对性能一直有着最高的需求, 但现在这个领域的专家开始大量使用比较慢的动态语言来完成日常工作。 33 | 我们相信有很多使用动态语言的理由, 所以我们不会舍弃这样的特性。幸运的是,现代语言设计和编译器技术使得为原型设计提供单一的高效开发环境, 34 | 并且配置高性能的应用成为可能。Julia 语言在这其中扮演了这样一个角色:作为灵活的动态语言,适合科学和数值计算,性能可与传统静态类型语言媲美。 35 | 36 | ```@raw html 37 | 41 | ``` 42 | 43 | 由于 Julia 的编译器和其它语言比如 Python 或 R 有所不同,一开始您或许会觉得 Julia 中什么样的代码运行效率高,什么样的代码运行效率低似乎并不很直观。 44 | 如果您发现 Julia 变慢了,我们非常建议您在尝试其它功能前读一下[提高性能的窍门](@ref man-performance-tips) 。只要您理解 Julia 的工作方式, 45 | 就会很容易地写出运行效率甚至可以和 C 相媲美的代码。 46 | 47 | ```@raw html 48 | 58 | ``` 59 | 60 | Julia 具有通过类型推倒和[即时编译(JIT)](https://en.wikipedia.org/wiki/Just-in-time_compilation)在[LLVM](https://en.wikipedia.org/wiki/Low_Level_Virtual_Machine)上实现的可选类型标注,多重派发,良好的性能。它是一个支持过程式,函数式 61 | 面向对象编程的多范式语言。它提供了简易和简洁的高等数值计算,它类似于 R 、 MATLAB 和 Python ,支持一般用途的编程。为了达到这个目的 62 | Julia 在数学编程语言的基础上,参考了不少流行动态语言,例如[Lisp](https://en.wikipedia.org/wiki/Lisp_(programming_language)), [Perl](https://en.wikipedia.org/wiki/Perl_(programming_language)), 63 | [Python](https://en.wikipedia.org/wiki/Python_(programming_language)), [Lua](https://en.wikipedia.org/wiki/Lua_(programming_language)), 64 | 和 [Ruby](https://en.wikipedia.org/wiki/Ruby_(programming_language))。 65 | 66 | ```@raw html 67 | 76 | ``` 77 | 78 | Julia 与传统动态语言最大的区别是: 79 | 80 | * 核心语言很小;标准库是用 Julia 本身写的,如整数运算在内的基础运算 81 | * 完善的类型,方便构造对象和做类型声明 82 | * 基于[多重派发](https://en.wikipedia.org/wiki/Multiple_dispatch)通过很多不同的参数类型来定义函数行为的能力 83 | * 为不同类型自动生成高效,专用的代码 84 | * 接近C语言的,良好的性能 85 | 86 | ```@raw html 87 | 94 | ``` 95 | 96 | 尽管,一些人有时说动态语言是“无类型的”,但实际上他们并不是这样:每一个对象,无论是基础的还是用户自己定义的,都有一个类型。 97 | 在大多数动态语言中都缺乏类型声明,而这往往意味着无法指示编译器值的类型,也就无法显示地讨论类型。另一方面,静态语言中,虽然可以标记类型 98 | (往往也必须这么做),但是类型只在编译时期才存在,而无法在运行时进行操作和表达。在 Julia 里,类型是它们自己的动态对象,也可以 99 | 被用来给编译器提供相应的信息。 100 | 101 | ```@raw html 102 | 109 | ``` 110 | 111 | 类型系统和多重派发是 Julia 语言最主要的特征(尽管类型和多重派发并不必要被显式使用):函数通过函数名称和不同类型变量的组合进行定义,然后在调用时会派发 112 | 最接近(most specific)的定义上去。这样的编程模型非常适合数学化的编程,尤其是在传统的面向对象派发中,一些函数的第一个变量理论上并不“拥有”这样一个操作时。 113 | 而在Julia中运算符只是函数的一个特殊标记——例如,为用户定义的新类型添加加法运算,你只要为`+`函数定义一个新的方法就可以了。 114 | 已有的代码就可以无缝接入这个新的类型。 115 | 116 | ```@raw html 117 | 123 | ``` 124 | 125 | 一部分是因为动态类型推导(可以被可选的类型标注增强),另一部分是因为在这个语言建立之初就对性能非常看重,Julia 的计算性能超过了其它的 126 | 动态语言,甚至能够与静态编译语言竞争。对于大型数值问题,速度一直都是,也一直会是一个重要的关注点:这些年以来,被处理的数据量的增长有着Moore定律。 127 | 128 | ```@raw html 129 | 144 | ``` 145 | 146 | Julia 的目标是创建一个前所未有的集易用、强大、高效于一体的语言。除此之外,Julia 的优势还在于: 147 | 148 | * 免费开源([MIT协议](https://github.com/JuliaLang/julia/blob/master/LICENSE.md)) 149 | * 用户定义的类型和内建类型一样快和兼容 150 | * 无需特意编写向量化的代码;非向量化的代码就很快 151 | * 为并行计算和分布式计算设计 152 | * 轻量级的“绿色”线程(([协程](https://en.wikipedia.org/wiki/Coroutine))) 153 | * 低调又牛逼的类型系统 154 | * 优雅、可扩展的类型转换 155 | * 高效支持[Unicode](https://en.wikipedia.org/wiki/Unicode),包括但不限于[UTF-8](https://en.wikipedia.org/wiki/UTF-8) 156 | * 直接调用 C 函数(不需封装或调用特别的 API) 157 | * 像 Shell 一样强大的管理其他进程的能力 158 | * 像 Lisp 一样的宏和其他元编程工具 159 | -------------------------------------------------------------------------------- /docs/src/manual/complex-and-rational-numbers.md: -------------------------------------------------------------------------------- 1 | # 复数与分数 2 | 3 | ```@raw html 4 | 5 | ``` 6 | 7 | Julia 语言自带预定义的表示复数与分数的类型,并且支持它们的各种[标准数学操作与基础函数](@ref)。由于也定义了复数与分数的[转换与提升](@ref conversion-and-promotion),因此对预定义数值类型(无论是原始的还是复合的)的任意组合进行的操作都会表现得如预期的一样。 8 | 9 | ```@raw html 10 | 14 | ``` 15 | 16 | ## 复数 17 | 18 | ```@raw html 19 | 20 | ``` 21 | 22 | 在Julia中,全局常量 [`im`](@ref) 被绑定到复数 *i*,表示 -1 的主平方根。由于 `i` 是一个很流行的用作索引的变量名,所以直接把它作为全局常量被认为是很危险的。由于 Julia 允许数值文本[作为系数与标识符并置](@ref man-numeric-literal-coefficients),这种绑定就足够为复数提供很方便的语法,类似于传统的数学记法: 23 | 24 | ```@raw html 25 | 30 | ``` 31 | 32 | ```jldoctest 33 | julia> 1 + 2im 34 | 1 + 2im 35 | ``` 36 | 37 | 你可以对复数进行各种标准算术操作: 38 | 39 | ```@raw html 40 | 41 | ``` 42 | 43 | ```jldoctest 44 | julia> (1 + 2im)*(2 - 3im) 45 | 8 + 1im 46 | 47 | julia> (1 + 2im)/(1 - 2im) 48 | -0.6 + 0.8im 49 | 50 | julia> (1 + 2im) + (1 - 2im) 51 | 2 + 0im 52 | 53 | julia> (-3 + 2im) - (5 - 1im) 54 | -8 + 3im 55 | 56 | julia> (-1 + 2im)^2 57 | -3 - 4im 58 | 59 | julia> (-1 + 2im)^2.5 60 | 2.7296244647840084 - 6.960664459571898im 61 | 62 | julia> (-1 + 2im)^(1 + 1im) 63 | -0.27910381075826657 + 0.08708053414102428im 64 | 65 | julia> 3(2 - 5im) 66 | 6 - 15im 67 | 68 | julia> 3(2 - 5im)^2 69 | -63 - 60im 70 | 71 | julia> 3(2 - 5im)^-1.0 72 | 0.20689655172413796 + 0.5172413793103449im 73 | ``` 74 | 75 | 类型提升机制也确保你可以使用不同类型的操作数的组合: 76 | 77 | ```@raw html 78 | 79 | ``` 80 | 81 | ```jldoctest 82 | julia> 2(1 - 1im) 83 | 2 - 2im 84 | 85 | julia> (2 + 3im) - 1 86 | 1 + 3im 87 | 88 | julia> (1 + 2im) + 0.5 89 | 1.5 + 2.0im 90 | 91 | julia> (2 + 3im) - 0.5im 92 | 2.0 + 2.5im 93 | 94 | julia> 0.75(1 + 2im) 95 | 0.75 + 1.5im 96 | 97 | julia> (2 + 3im) / 2 98 | 1.0 + 1.5im 99 | 100 | julia> (1 - 3im) / (2 + 2im) 101 | -0.5 - 1.0im 102 | 103 | julia> 2im^2 104 | -2 + 0im 105 | 106 | julia> 1 + 3/4im 107 | 1.0 - 0.75im 108 | ``` 109 | 110 | 注意 `3/4im == 3/(4*im) == -(3/4*im)`,因为文本系数比除法的优先级更高。 111 | 112 | ```@raw html 113 | 115 | ``` 116 | 117 | Julia 提供了一些用来操作复数值的标准函数: 118 | 119 | ```@raw html 120 | 121 | ``` 122 | 123 | ```jldoctest 124 | julia> z = 1 + 2im 125 | 1 + 2im 126 | 127 | julia> real(1 + 2im) # real part of z 128 | 1 129 | 130 | julia> imag(1 + 2im) # imaginary part of z 131 | 2 132 | 133 | julia> conj(1 + 2im) # complex conjugate of z 134 | 1 - 2im 135 | 136 | julia> abs(1 + 2im) # absolute value of z 137 | 2.23606797749979 138 | 139 | julia> abs2(1 + 2im) # squared absolute value 140 | 5 141 | 142 | julia> angle(1 + 2im) # phase angle in radians 143 | 1.1071487177940904 144 | ``` 145 | 146 | 按照惯例,复数的绝对值([`abs`](@ref))是从零点到它的距离。[`abs2`](@ref) 给出绝对值的平方,作用于复数上时非常有用,可以避免做平方根的操作。[`angle`] 返回以弧度为单位的相位角(这也被称为辐角函数)。所有其它的[基础函数](@ref)在复数上也都有完整的定义: 147 | 148 | ```@raw html 149 | 154 | ``` 155 | 156 | ```jldoctest 157 | julia> sqrt(1im) 158 | 0.7071067811865476 + 0.7071067811865475im 159 | 160 | julia> sqrt(1 + 2im) 161 | 1.272019649514069 + 0.7861513777574233im 162 | 163 | julia> cos(1 + 2im) 164 | 2.0327230070196656 - 3.0518977991518im 165 | 166 | julia> exp(1 + 2im) 167 | -1.1312043837568135 + 2.4717266720048188im 168 | 169 | julia> sinh(1 + 2im) 170 | -0.4890562590412937 + 1.4031192506220405im 171 | ``` 172 | 173 | 注意数学函数通常应用于实数就返回实数值,应用于复数就返回复数值。例如,当 [`sqrt`](@ref) 应用于 `-1` 与 `-1 + 0im` 会有不同的表现,虽然 `-1 == -1 + 0im`: 174 | 175 | ```@raw html 176 | 179 | ``` 180 | 181 | ```jldoctest 182 | julia> sqrt(-1) 183 | ERROR: DomainError with -1.0: 184 | sqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x)). 185 | Stacktrace: 186 | [...] 187 | 188 | julia> sqrt(-1 + 0im) 189 | 0.0 + 1.0im 190 | ``` 191 | 192 | 从变量构建复数时,[文本型数值系数记法](@ref man-numeric-literal-coefficients)不再适用。相反地,乘法必须显式地写出: 193 | 194 | ```@raw html 195 | 197 | ``` 198 | 199 | ```jldoctest 200 | julia> a = 1; b = 2; a + b*im 201 | 1 + 2im 202 | ``` 203 | 204 | 然而,我们**并不**推荐这样,而应改为使用 [`complex`](@ref) 函数直接通过实部与虚部构建一个复数值: 205 | 206 | ```@raw html 207 | 209 | ``` 210 | 211 | ```jldoctest 212 | julia> a = 1; b = 2; complex(a, b) 213 | 1 + 2im 214 | ``` 215 | 216 | 这种构建避免了乘法和加法操作。 217 | 218 | ```@raw html 219 | 220 | ``` 221 | 222 | [`Inf`](@ref) 和 [`NaN`](@ref) 可能出现在复数的实部和虚部,正如[特殊的浮点值](@ref)章节所描述的: 223 | 224 | ```@raw html 225 | 227 | ``` 228 | 229 | ```jldoctest 230 | julia> 1 + Inf*im 231 | 1.0 + Inf*im 232 | 233 | julia> 1 + NaN*im 234 | 1.0 + NaN*im 235 | ``` 236 | 237 | ## 分数 238 | 239 | ```@raw html 240 | 241 | ``` 242 | 243 | Julia 有一个用于表示整数精确比值的分数类型。分数通过 [`//`](@ref) 运算符构建: 244 | 245 | ```@raw html 246 | 248 | ``` 249 | 250 | ```jldoctest 251 | julia> 2//3 252 | 2//3 253 | ``` 254 | 255 | 如果一个分数的分子和分母含有公因子,它们会被约分到最简形式且分母非负: 256 | 257 | ```@raw html 258 | 260 | ``` 261 | 262 | ```jldoctest 263 | julia> 6//9 264 | 2//3 265 | 266 | julia> -4//8 267 | -1//2 268 | 269 | julia> 5//-15 270 | -1//3 271 | 272 | julia> -4//-12 273 | 1//3 274 | ``` 275 | 276 | 277 | 整数比值的这种标准化形式是唯一的,所以分数值的相等性可由校验分子与分母都相等来测试。分数值的标准化分子和分母可以使用 [`numerator`](@ref) 和 [`denominator`](@ref) 函数得到: 278 | 279 | ```@raw html 280 | 284 | ``` 285 | 286 | ```jldoctest 287 | julia> numerator(2//3) 288 | 2 289 | 290 | julia> denominator(2//3) 291 | 3 292 | ``` 293 | 294 | 分子和分母的直接比较通常是不必要的,因为标准算术和比较操作对分数值也有定义: 295 | 296 | ```@raw html 297 | 299 | ``` 300 | 301 | ```jldoctest 302 | julia> 2//3 == 6//9 303 | true 304 | 305 | julia> 2//3 == 9//27 306 | false 307 | 308 | julia> 3//7 < 1//2 309 | true 310 | 311 | julia> 3//4 > 2//3 312 | true 313 | 314 | julia> 2//4 + 1//6 315 | 2//3 316 | 317 | julia> 5//12 - 1//4 318 | 1//6 319 | 320 | julia> 5//8 * 3//12 321 | 5//32 322 | 323 | julia> 6//5 / 10//7 324 | 21//25 325 | ``` 326 | 327 | 分数可以很容易地被转换成浮点数: 328 | 329 | ```@raw html 330 | 331 | ``` 332 | 333 | ```jldoctest 334 | julia> float(3//4) 335 | 0.75 336 | ``` 337 | 338 | 对任意整数值 `a` 和 `b`(除了 `a == 0` 且 `b == 0` 时),从分数到浮点数的转换遵从以下的一致性: 339 | 340 | ```@raw html 341 | 343 | ``` 344 | 345 | ```jldoctest 346 | julia> a = 1; b = 2; 347 | 348 | julia> isequal(float(a//b), a/b) 349 | true 350 | ``` 351 | 352 | Julia接受构建无穷分数值: 353 | 354 | ```@raw html 355 | 356 | ``` 357 | 358 | ```jldoctest 359 | julia> 5//0 360 | 1//0 361 | 362 | julia> -3//0 363 | -1//0 364 | 365 | julia> typeof(ans) 366 | Rational{Int64} 367 | ``` 368 | 369 | 但不接受试图构建一个 [`NaN`](@ref) 分数值: 370 | 371 | ```@raw html 372 | 373 | ``` 374 | 375 | ```jldoctest 376 | julia> 0//0 377 | ERROR: ArgumentError: invalid rational: zero(Int64)//zero(Int64) 378 | Stacktrace: 379 | [...] 380 | ``` 381 | 382 | 像往常一样,类型提升系统使得分数可以轻松地同其它数值类型进行交互: 383 | 384 | ```@raw html 385 | 386 | ``` 387 | 388 | ```jldoctest 389 | julia> 3//5 + 1 390 | 8//5 391 | 392 | julia> 3//5 - 0.5 393 | 0.09999999999999998 394 | 395 | julia> 2//7 * (1 + 2im) 396 | 2//7 + 4//7*im 397 | 398 | julia> 2//7 * (1.5 + 2im) 399 | 0.42857142857142855 + 0.5714285714285714im 400 | 401 | julia> 3//2 / (1 + 2im) 402 | 3//10 - 3//5*im 403 | 404 | julia> 1//2 + 2im 405 | 1//2 + 2//1*im 406 | 407 | julia> 1 + 2//3im 408 | 1//1 - 2//3*im 409 | 410 | julia> 0.5 == 1//2 411 | true 412 | 413 | julia> 0.33 == 1//3 414 | false 415 | 416 | julia> 0.33 < 1//3 417 | true 418 | 419 | julia> 1//3 - 0.33 420 | 0.0033333333333332993 421 | ``` 422 | -------------------------------------------------------------------------------- /docs/src/manual/mathematical-operations.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # 数学运算和基础操作 4 | 5 | 8 | 9 | Julia 为它所有的基础数值类型,提供了整套的基础算术和位运算,也提供了一套高效、可移植的标准数学函数。 10 | 11 | 12 | # 算术运算符 13 | 14 | The following [arithmetic operators](https://en.wikipedia.org/wiki/Arithmetic#Arithmetic_operations) 15 | are supported on all primitive numeric types: 16 | 17 | | Expression | Name | Description | 18 | |:---------- |:-------------- |:-------------------------------------- | 19 | | `+x` | unary plus | the identity operation | 20 | | `-x` | unary minus | maps values to their additive inverses | 21 | | `x + y` | binary plus | performs addition | 22 | | `x - y` | binary minus | performs subtraction | 23 | | `x * y` | times | performs multiplication | 24 | | `x / y` | divide | performs division | 25 | | `x ÷ y` | integer divide | x / y, truncated to an integer | 26 | | `x \ y` | inverse divide | equivalent to `y / x` | 27 | | `x ^ y` | power | raises `x` to the `y`th power | 28 | | `x % y` | remainder | equivalent to `rem(x,y)` | 29 | 30 | as well as the negation on [`Bool`](@ref) types: 31 | 32 | | Expression | Name | Description | 33 | |:---------- |:-------- |:---------------------------------------- | 34 | | `!x` | negation | changes `true` to `false` and vice versa | 35 | 36 | Julia's promotion system makes arithmetic operations on mixtures of argument types "just work" 37 | naturally and automatically. See [Conversion and Promotion](@ref conversion-and-promotion) for details of the promotion 38 | system. 39 | 40 | Here are some simple examples using arithmetic operators: 41 | 42 | ```jldoctest 43 | julia> 1 + 2 + 3 44 | 6 45 | 46 | julia> 1 - 2 47 | -1 48 | 49 | julia> 3*2/12 50 | 0.5 51 | ``` 52 | 53 | (By convention, we tend to space operators more tightly if they get applied before other nearby 54 | operators. For instance, we would generally write `-x + 2` to reflect that first `x` gets negated, 55 | and then `2` is added to that result.) 56 | 57 | ## Bitwise Operators 58 | 59 | The following [bitwise operators](https://en.wikipedia.org/wiki/Bitwise_operation#Bitwise_operators) 60 | are supported on all primitive integer types: 61 | 62 | | Expression | Name | 63 | |:---------- |:------------------------------------------------------------------------ | 64 | | `~x` | bitwise not | 65 | | `x & y` | bitwise and | 66 | | `x \| y` | bitwise or | 67 | | `x ⊻ y` | bitwise xor (exclusive or) | 68 | | `x >>> y` | [logical shift](https://en.wikipedia.org/wiki/Logical_shift) right | 69 | | `x >> y` | [arithmetic shift](https://en.wikipedia.org/wiki/Arithmetic_shift) right | 70 | | `x << y` | logical/arithmetic shift left | 71 | 72 | Here are some examples with bitwise operators: 73 | 74 | ```jldoctest 75 | julia> ~123 76 | -124 77 | 78 | julia> 123 & 234 79 | 106 80 | 81 | julia> 123 | 234 82 | 251 83 | 84 | julia> 123 ⊻ 234 85 | 145 86 | 87 | julia> xor(123, 234) 88 | 145 89 | 90 | julia> ~UInt32(123) 91 | 0xffffff84 92 | 93 | julia> ~UInt8(123) 94 | 0x84 95 | ``` 96 | 97 | ## Updating operators 98 | 99 | Every binary arithmetic and bitwise operator also has an updating version that assigns the result 100 | of the operation back into its left operand. The updating version of the binary operator is formed 101 | by placing a `=` immediately after the operator. For example, writing `x += 3` is equivalent to 102 | writing `x = x + 3`: 103 | 104 | ```jldoctest 105 | julia> x = 1 106 | 1 107 | 108 | julia> x += 3 109 | 4 110 | 111 | julia> x 112 | 4 113 | ``` 114 | 115 | The updating versions of all the binary arithmetic and bitwise operators are: 116 | 117 | ``` 118 | += -= *= /= \= ÷= %= ^= &= |= ⊻= >>>= >>= <<= 119 | ``` 120 | 121 | !!! note 122 | An updating operator rebinds the variable on the left-hand side. As a result, the type of the 123 | variable may change. 124 | 125 | ```jldoctest 126 | julia> x = 0x01; typeof(x) 127 | UInt8 128 | 129 | julia> x *= 2 # Same as x = x * 2 130 | 2 131 | 132 | julia> typeof(x) 133 | Int64 134 | ``` 135 | 136 | ## [Vectorized "dot" operators](@id man-dot-operators) 137 | 138 | For *every* binary operation like `^`, there is a corresponding 139 | "dot" operation `.^` that is *automatically* defined 140 | to perform `^` element-by-element on arrays. For example, 141 | `[1,2,3] ^ 3` is not defined, since there is no standard 142 | mathematical meaning to "cubing" a (non-square) array, but 143 | `[1,2,3] .^ 3` is defined as computing the elementwise 144 | (or "vectorized") result `[1^3, 2^3, 3^3]`. Similarly for unary 145 | operators like `!` or `√`, there is a corresponding `.√` that 146 | applies the operator elementwise. 147 | 148 | ```jldoctest 149 | julia> [1,2,3] .^ 3 150 | 3-element Array{Int64,1}: 151 | 1 152 | 8 153 | 27 154 | ``` 155 | 156 | More specifically, `a .^ b` is parsed as the ["dot" call](@ref man-vectorized) 157 | `(^).(a,b)`, which performs a [broadcast](@ref Broadcasting) operation: 158 | it can combine arrays and scalars, arrays of the same size (performing 159 | the operation elementwise), and even arrays of different shapes (e.g. 160 | combining row and column vectors to produce a matrix). Moreover, like 161 | all vectorized "dot calls," these "dot operators" are 162 | *fusing*. For example, if you compute `2 .* A.^2 .+ sin.(A)` (or 163 | equivalently `@. 2A^2 + sin(A)`, using the [`@.`](@ref @__dot__) macro) for 164 | an array `A`, it performs a *single* loop over `A`, computing `2a^2 + sin(a)` 165 | for each element of `A`. In particular, nested dot calls like `f.(g.(x))` 166 | are fused, and "adjacent" binary operators like `x .+ 3 .* x.^2` are 167 | equivalent to nested dot calls `(+).(x, (*).(3, (^).(x, 2)))`. 168 | 169 | Furthermore, "dotted" updating operators like `a .+= b` (or `@. a += b`) are parsed 170 | as `a .= a .+ b`, where `.=` is a fused *in-place* assignment operation 171 | (see the [dot syntax documentation](@ref man-vectorized)). 172 | 173 | Note the dot syntax is also applicable to user-defined operators. 174 | For example, if you define `⊗(A,B) = kron(A,B)` to give a convenient 175 | infix syntax `A ⊗ B` for Kronecker products ([`kron`](@ref)), then 176 | `[A,B] .⊗ [C,D]` will compute `[A⊗C, B⊗D]` with no additional coding. 177 | 178 | Combining dot operators with numeric literals can be ambiguous. 179 | For example, it is not clear whether `1.+x` means `1. + x` or `1 .+ x`. 180 | Therefore this syntax is disallowed, and spaces must be used around 181 | the operator in such cases. 182 | 183 | ## Numeric Comparisons 184 | 185 | Standard comparison operations are defined for all the primitive numeric types: 186 | 187 | | Operator | Name | 188 | |:---------------------------- |:------------------------ | 189 | | [`==`](@ref) | equality | 190 | | [`!=`](@ref), [`≠`](@ref !=) | inequality | 191 | | [`<`](@ref) | less than | 192 | | [`<=`](@ref), [`≤`](@ref <=) | less than or equal to | 193 | | [`>`](@ref) | greater than | 194 | | [`>=`](@ref), [`≥`](@ref >=) | greater than or equal to | 195 | 196 | Here are some simple examples: 197 | 198 | ```jldoctest 199 | julia> 1 == 1 200 | true 201 | 202 | julia> 1 == 2 203 | false 204 | 205 | julia> 1 != 2 206 | true 207 | 208 | julia> 1 == 1.0 209 | true 210 | 211 | julia> 1 < 2 212 | true 213 | 214 | julia> 1.0 > 3 215 | false 216 | 217 | julia> 1 >= 1.0 218 | true 219 | 220 | julia> -1 <= 1 221 | true 222 | 223 | julia> -1 <= -1 224 | true 225 | 226 | julia> -1 <= -2 227 | false 228 | 229 | julia> 3 < -0.5 230 | false 231 | ``` 232 | 233 | Integers are compared in the standard manner -- by comparison of bits. Floating-point numbers 234 | are compared according to the [IEEE 754 standard](https://en.wikipedia.org/wiki/IEEE_754-2008): 235 | 236 | * Finite numbers are ordered in the usual manner. 237 | * Positive zero is equal but not greater than negative zero. 238 | * `Inf` is equal to itself and greater than everything else except `NaN`. 239 | * `-Inf` is equal to itself and less then everything else except `NaN`. 240 | * `NaN` is not equal to, not less than, and not greater than anything, including itself. 241 | 242 | The last point is potentially surprising and thus worth noting: 243 | 244 | ```jldoctest 245 | julia> NaN == NaN 246 | false 247 | 248 | julia> NaN != NaN 249 | true 250 | 251 | julia> NaN < NaN 252 | false 253 | 254 | julia> NaN > NaN 255 | false 256 | ``` 257 | 258 | and can cause especial headaches with [arrays](@ref man-multi-dim-arrays): 259 | 260 | ```jldoctest 261 | julia> [1 NaN] == [1 NaN] 262 | false 263 | ``` 264 | 265 | Julia provides additional functions to test numbers for special values, which can be useful in 266 | situations like hash key comparisons: 267 | 268 | | Function | Tests if | 269 | |:----------------------- |:------------------------- | 270 | | [`isequal(x, y)`](@ref) | `x` and `y` are identical | 271 | | [`isfinite(x)`](@ref) | `x` is a finite number | 272 | | [`isinf(x)`](@ref) | `x` is infinite | 273 | | [`isnan(x)`](@ref) | `x` is not a number | 274 | 275 | [`isequal`](@ref) considers `NaN`s equal to each other: 276 | 277 | ```jldoctest 278 | julia> isequal(NaN, NaN) 279 | true 280 | 281 | julia> isequal([1 NaN], [1 NaN]) 282 | true 283 | 284 | julia> isequal(NaN, NaN32) 285 | true 286 | ``` 287 | 288 | `isequal` can also be used to distinguish signed zeros: 289 | 290 | ```jldoctest 291 | julia> -0.0 == 0.0 292 | true 293 | 294 | julia> isequal(-0.0, 0.0) 295 | false 296 | ``` 297 | 298 | Mixed-type comparisons between signed integers, unsigned integers, and floats can be tricky. A 299 | great deal of care has been taken to ensure that Julia does them correctly. 300 | 301 | For other types, `isequal` defaults to calling [`==`](@ref), so if you want to define 302 | equality for your own types then you only need to add a [`==`](@ref) method. If you define 303 | your own equality function, you should probably define a corresponding [`hash`](@ref) method 304 | to ensure that `isequal(x,y)` implies `hash(x) == hash(y)`. 305 | 306 | ### Chaining comparisons 307 | 308 | Unlike most languages, with the [notable exception of Python](https://en.wikipedia.org/wiki/Python_syntax_and_semantics#Comparison_operators), 309 | comparisons can be arbitrarily chained: 310 | 311 | ```jldoctest 312 | julia> 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 313 | true 314 | ``` 315 | 316 | Chaining comparisons is often quite convenient in numerical code. Chained comparisons use the 317 | `&&` operator for scalar comparisons, and the [`&`](@ref) operator for elementwise comparisons, 318 | which allows them to work on arrays. For example, `0 .< A .< 1` gives a boolean array whose entries 319 | are true where the corresponding elements of `A` are between 0 and 1. 320 | 321 | Note the evaluation behavior of chained comparisons: 322 | 323 | ```jldoctest 324 | julia> v(x) = (println(x); x) 325 | v (generic function with 1 method) 326 | 327 | julia> v(1) < v(2) <= v(3) 328 | 2 329 | 1 330 | 3 331 | true 332 | 333 | julia> v(1) > v(2) <= v(3) 334 | 2 335 | 1 336 | false 337 | ``` 338 | 339 | The middle expression is only evaluated once, rather than twice as it would be if the expression 340 | were written as `v(1) < v(2) && v(2) <= v(3)`. However, the order of evaluations in a chained 341 | comparison is undefined. It is strongly recommended not to use expressions with side effects (such 342 | as printing) in chained comparisons. If side effects are required, the short-circuit `&&` operator 343 | should be used explicitly (see [Short-Circuit Evaluation](@ref)). 344 | 345 | ### Elementary Functions 346 | 347 | Julia provides a comprehensive collection of mathematical functions and operators. These mathematical 348 | operations are defined over as broad a class of numerical values as permit sensible definitions, 349 | including integers, floating-point numbers, rationals, and complex numbers, 350 | wherever such definitions make sense. 351 | 352 | Moreover, these functions (like any Julia function) can be applied in "vectorized" fashion to 353 | arrays and other collections with the [dot syntax](@ref man-vectorized) `f.(A)`, 354 | e.g. `sin.(A)` will compute the sine of each element of an array `A`. 355 | 356 | ## Operator Precedence and Associativity 357 | 358 | Julia applies the following order and associativity of operations, from highest precedence to lowest: 359 | 360 | | Category | Operators | Associativity | 361 | |:-------------- |:------------------------------------------------------------------------------------------------- |:-------------------------- | 362 | | Syntax | `.` followed by `::` | Left | 363 | | Exponentiation | `^` | Right | 364 | | Unary | `+ - √` | Right[^1] | 365 | | Fractions | `//` | Left | 366 | | Multiplication | `* / % & \ ÷` | Left[^2] | 367 | | Bitshifts | `<< >> >>>` | Left | 368 | | Addition | `+ - \| ⊻` | Left[^2] | 369 | | Syntax | `: ..` | Left | 370 | | Syntax | `\|>` | Left | 371 | | Syntax | `<\|` | Right | 372 | | Comparisons | `> < >= <= == === != !== <:` | Non-associative | 373 | | Control flow | `&&` followed by `\|\|` followed by `?` | Right | 374 | | Pair | `=>` | Right | 375 | | Assignments | `= += -= *= /= //= \= ^= ÷= %= \|= &= ⊻= <<= >>= >>>=` | Right | 376 | 377 | [^1]: 378 | The unary operators `+` and `-` require explicit parentheses around their argument to disambiguate them from the operator `++`, etc. Other compositions of unary operators are parsed with right-associativity, e. g., `√√-a` as `√(√(-a))`. 379 | [^2]: 380 | The operators `+`, `++` and `*` are non-associative. `a + b + c` is parsed as `+(a, b, c)` not `+(+(a, b), 381 | c)`. However, the fallback methods for `+(a, b, c, d...)` and `*(a, b, c, d...)` both default to left-associative evaluation. 382 | 383 | For a complete list of *every* Julia operator's precedence, see the top of this file: 384 | [`src/julia-parser.scm`](https://github.com/JuliaLang/julia/blob/master/src/julia-parser.scm) 385 | 386 | You can also find the numerical precedence for any given operator via the built-in function `Base.operator_precedence`, where higher numbers take precedence: 387 | 388 | ```jldoctest 389 | julia> Base.operator_precedence(:+), Base.operator_precedence(:*), Base.operator_precedence(:.) 390 | (11, 13, 17) 391 | 392 | julia> Base.operator_precedence(:sin), Base.operator_precedence(:+=), Base.operator_precedence(:(=)) # (Note the necessary parens on `:(=)`) 393 | (0, 1, 1) 394 | ``` 395 | 396 | A symbol representing the operator associativity can also be found by calling the built-in function `Base.operator_associativity`: 397 | 398 | ```jldoctest 399 | julia> Base.operator_associativity(:-), Base.operator_associativity(:+), Base.operator_associativity(:^) 400 | (:left, :none, :right) 401 | 402 | julia> Base.operator_associativity(:⊗), Base.operator_associativity(:sin), Base.operator_associativity(:→) 403 | (:left, :none, :right) 404 | ``` 405 | 406 | Note that symbols such as `:sin` return precedence `0`. This value represents invalid operators and not 407 | operators of lowest precedence. Similarly, such operators are assigned associativity `:none`. 408 | 409 | ## Numerical Conversions 410 | 411 | Julia supports three forms of numerical conversion, which differ in their handling of inexact 412 | conversions. 413 | 414 | * The notation `T(x)` or `convert(T,x)` converts `x` to a value of type `T`. 415 | 416 | * If `T` is a floating-point type, the result is the nearest representable value, which could be 417 | positive or negative infinity. 418 | * If `T` is an integer type, an `InexactError` is raised if `x` is not representable by `T`. 419 | * `x % T` converts an integer `x` to a value of integer type `T` congruent to `x` modulo `2^n`, 420 | where `n` is the number of bits in `T`. In other words, the binary representation is truncated 421 | to fit. 422 | * The [Rounding functions](@ref) take a type `T` as an optional argument. For example, `round(Int,x)` 423 | is a shorthand for `Int(round(x))`. 424 | 425 | The following examples show the different forms. 426 | 427 | ```jldoctest 428 | julia> Int8(127) 429 | 127 430 | 431 | julia> Int8(128) 432 | ERROR: InexactError: trunc(Int8, 128) 433 | Stacktrace: 434 | [...] 435 | 436 | julia> Int8(127.0) 437 | 127 438 | 439 | julia> Int8(3.14) 440 | ERROR: InexactError: Int8(Int8, 3.14) 441 | Stacktrace: 442 | [...] 443 | 444 | julia> Int8(128.0) 445 | ERROR: InexactError: Int8(Int8, 128.0) 446 | Stacktrace: 447 | [...] 448 | 449 | julia> 127 % Int8 450 | 127 451 | 452 | julia> 128 % Int8 453 | -128 454 | 455 | julia> round(Int8,127.4) 456 | 127 457 | 458 | julia> round(Int8,127.6) 459 | ERROR: InexactError: trunc(Int8, 128.0) 460 | Stacktrace: 461 | [...] 462 | ``` 463 | 464 | See [Conversion and Promotion](@ref conversion-and-promotion) for how to define your own conversions and promotions. 465 | 466 | ### Rounding functions 467 | 468 | | Function | Description | Return type | 469 | |:--------------------- |:-------------------------------- |:----------- | 470 | | [`round(x)`](@ref) | round `x` to the nearest integer | `typeof(x)` | 471 | | [`round(T, x)`](@ref) | round `x` to the nearest integer | `T` | 472 | | [`floor(x)`](@ref) | round `x` towards `-Inf` | `typeof(x)` | 473 | | [`floor(T, x)`](@ref) | round `x` towards `-Inf` | `T` | 474 | | [`ceil(x)`](@ref) | round `x` towards `+Inf` | `typeof(x)` | 475 | | [`ceil(T, x)`](@ref) | round `x` towards `+Inf` | `T` | 476 | | [`trunc(x)`](@ref) | round `x` towards zero | `typeof(x)` | 477 | | [`trunc(T, x)`](@ref) | round `x` towards zero | `T` | 478 | 479 | ### Division functions 480 | 481 | | Function | Description | 482 | |:------------------------- |:--------------------------------------------------------------------------------------------------------- | 483 | | [`div(x,y)`](@ref), `x÷y` | truncated division; quotient rounded towards zero | 484 | | [`fld(x,y)`](@ref) | floored division; quotient rounded towards `-Inf` | 485 | | [`cld(x,y)`](@ref) | ceiling division; quotient rounded towards `+Inf` | 486 | | [`rem(x,y)`](@ref) | remainder; satisfies `x == div(x,y)*y + rem(x,y)`; sign matches `x` | 487 | | [`mod(x,y)`](@ref) | modulus; satisfies `x == fld(x,y)*y + mod(x,y)`; sign matches `y` | 488 | | [`mod1(x,y)`](@ref) | `mod` with offset 1; returns `r∈(0,y]` for `y>0` or `r∈[y,0)` for `y<0`, where `mod(r, y) == mod(x, y)` | 489 | | [`mod2pi(x)`](@ref) | modulus with respect to 2pi; `0 <= mod2pi(x)   < 2pi` | 490 | | [`divrem(x,y)`](@ref) | returns `(div(x,y),rem(x,y))` | 491 | | [`fldmod(x,y)`](@ref) | returns `(fld(x,y),mod(x,y))` | 492 | | [`gcd(x,y...)`](@ref) | greatest positive common divisor of `x`, `y`,... | 493 | | [`lcm(x,y...)`](@ref) | least positive common multiple of `x`, `y`,... | 494 | 495 | ### Sign and absolute value functions 496 | 497 | | Function | Description | 498 | |:----------------------- |:---------------------------------------------------------- | 499 | | [`abs(x)`](@ref) | a positive value with the magnitude of `x` | 500 | | [`abs2(x)`](@ref) | the squared magnitude of `x` | 501 | | [`sign(x)`](@ref) | indicates the sign of `x`, returning -1, 0, or +1 | 502 | | [`signbit(x)`](@ref) | indicates whether the sign bit is on (true) or off (false) | 503 | | [`copysign(x,y)`](@ref) | a value with the magnitude of `x` and the sign of `y` | 504 | | [`flipsign(x,y)`](@ref) | a value with the magnitude of `x` and the sign of `x*y` | 505 | 506 | ### Powers, logs and roots 507 | 508 | | Function | Description | 509 | |:------------------------ |:-------------------------------------------------------------------------- | 510 | | [`sqrt(x)`](@ref), `√x` | square root of `x` | 511 | | [`cbrt(x)`](@ref), `∛x` | cube root of `x` | 512 | | [`hypot(x,y)`](@ref) | hypotenuse of right-angled triangle with other sides of length `x` and `y` | 513 | | [`exp(x)`](@ref) | natural exponential function at `x` | 514 | | [`expm1(x)`](@ref) | accurate `exp(x)-1` for `x` near zero | 515 | | [`ldexp(x,n)`](@ref) | `x*2^n` computed efficiently for integer values of `n` | 516 | | [`log(x)`](@ref) | natural logarithm of `x` | 517 | | [`log(b,x)`](@ref) | base `b` logarithm of `x` | 518 | | [`log2(x)`](@ref) | base 2 logarithm of `x` | 519 | | [`log10(x)`](@ref) | base 10 logarithm of `x` | 520 | | [`log1p(x)`](@ref) | accurate `log(1+x)` for `x` near zero | 521 | | [`exponent(x)`](@ref) | binary exponent of `x` | 522 | | [`significand(x)`](@ref) | binary significand (a.k.a. mantissa) of a floating-point number `x` | 523 | 524 | For an overview of why functions like [`hypot`](@ref), [`expm1`](@ref), and [`log1p`](@ref) 525 | are necessary and useful, see John D. Cook's excellent pair of blog posts on the subject: [expm1, log1p, erfc](https://www.johndcook.com/blog/2010/06/07/math-library-functions-that-seem-unnecessary/), 526 | and [hypot](https://www.johndcook.com/blog/2010/06/02/whats-so-hard-about-finding-a-hypotenuse/). 527 | 528 | ### Trigonometric and hyperbolic functions 529 | 530 | All the standard trigonometric and hyperbolic functions are also defined: 531 | 532 | ``` 533 | sin cos tan cot sec csc 534 | sinh cosh tanh coth sech csch 535 | asin acos atan acot asec acsc 536 | asinh acosh atanh acoth asech acsch 537 | sinc cosc 538 | ``` 539 | 540 | These are all single-argument functions, with [`atan`](@ref) also accepting two arguments 541 | corresponding to a traditional [`atan2`](https://en.wikipedia.org/wiki/Atan2) function. 542 | 543 | Additionally, [`sinpi(x)`](@ref) and [`cospi(x)`](@ref) are provided for more accurate computations 544 | of [`sin(pi*x)`](@ref) and [`cos(pi*x)`](@ref) respectively. 545 | 546 | In order to compute trigonometric functions with degrees instead of radians, suffix the function 547 | with `d`. For example, [`sind(x)`](@ref) computes the sine of `x` where `x` is specified in degrees. 548 | The complete list of trigonometric functions with degree variants is: 549 | 550 | ``` 551 | sind cosd tand cotd secd cscd 552 | asind acosd atand acotd asecd acscd 553 | ``` 554 | 555 | ### Special functions 556 | 557 | Many other special mathematical functions are provided by the package 558 | [SpecialFunctions.jl](https://github.com/JuliaMath/SpecialFunctions.jl). 559 | -------------------------------------------------------------------------------- /docs/src/manual/style-guide.md: -------------------------------------------------------------------------------- 1 | # 代码风格指南 2 | 3 | ```@raw html 4 | 5 | ``` 6 | 7 | 接下来的部分将介绍如何写出具有Julia风格的代码。当然,这些规则并不是绝对的,它们只是一些建议,以便更好地帮助你熟悉这门语言,以及在不同的代码设计中做出选择。 8 | 9 | ```@raw html 10 | 11 | ``` 12 | 13 | ## 写函数,而不是仅仅写脚本 14 | 15 | ```@raw html 16 | 17 | ``` 18 | 19 | 一开始解决问题的时候,直接从最外层一步步写代码的确很便捷,但你应该尽早地将代码组织成函数。函数有更强的复用性和可测试性,并且能更清楚地让人知道哪些步骤做完了,以及每一步骤的输入输出分别是什么。此外,由于Julia编译器特殊的工作方式,写在函数中的代码往往要比最外层的代码运行地快得多。 20 | 21 | ```@raw html 22 | 27 | ``` 28 | 29 | 此外值得一提的是,函数应当接受参数,而不是直接使用全局变量( [`pi`](@ref) 等常数除外)进行操作。 30 | 31 | ```@raw html 32 | 34 | ``` 35 | 36 | ## 避免写过于特定的类型 37 | 38 | ```@raw html 39 | 40 | ``` 41 | 42 | 代码应该写得尽可能通用。例如,下面这段代码: 43 | 44 | ```@raw html 45 | 46 | ``` 47 | 48 | ```julia 49 | convert(Complex{Float64}, x) 50 | ``` 51 | 52 | 更好的写法是写成下面的通用函数: 53 | 54 | ```@raw html 55 | 56 | ``` 57 | 58 | ```julia 59 | complex(float(x)) 60 | ``` 61 | 62 | 上面的版本会把 `x` 转换成一个合适的类型,而非总是同一类型。 63 | 64 | ```@raw html 65 | 66 | ``` 67 | 68 | 这种代码风格与函数的参数尤其相关。例如,当一个参数可以是任何整型时,不要将它的类型声明为 `Int` 或 [`Int32`](@ref),而要使用抽象类型(abstract type)[`Integer`](@ref) 来表示。事实上,除非确实需要将其与其它的方法定义区分开,很多情况下你可以干脆完全省略掉参数的类型,因为如果你的操作中有不支持某种参数类型的操作的话,反正都会抛出 [`MethodError`](@ref) 的。这也称作 [鸭子类型](https://zh.wikipedia.org/wiki/%E9%B8%AD%E5%AD%90%E7%B1%BB%E5%9E%8B))。 69 | 70 | ```@raw html 71 | 78 | ``` 79 | 80 | 例如,考虑这样的一个叫做 `addone` 的函数,其返回值为它的参数加 1 : 81 | 82 | ```@raw html 83 | 85 | ``` 86 | 87 | ```julia 88 | addone(x::Int) = x + 1 # works only for Int 89 | addone(x::Integer) = x + oneunit(x) # any integer type 90 | addone(x::Number) = x + oneunit(x) # any numeric type 91 | addone(x) = x + oneunit(x) # any type supporting + and oneunit 92 | ``` 93 | 94 | 最后一种定义可以处理所有支持 [`oneunit`](@ref) (返回和 `x` 相同类型的 1,以避免不需要的类型提升(type promotion))以及 [`+`](@ref) 函数的类型。这里的关键点在于,**只**定义通用的 `addone(x) = x + oneunit(x)` 并**不会**带来性能上的损失,因为 Julia 会在需要的时候自动编译特定的版本。比如说,当第一次调用 `addone(12)` 时,Julia 会自动编译一个特定的 `addone` 函数,它接受一个 `x::Int` 的参数,并把调用的 `oneunit` 替换为内连的值 `1`。因此,上述的前三种 `addone` 的定义对于第四种来说是完全多余的。 95 | 96 | ```@raw html 97 | 105 | ``` 106 | 107 | ## 让调用者处理多余的参数多样性 108 | 109 | ```@raw html 110 | 111 | ``` 112 | 113 | 如下的代码: 114 | 115 | ```@raw html 116 | 117 | ``` 118 | 119 | ```julia 120 | function foo(x, y) 121 | x = Int(x); y = Int(y) 122 | ... 123 | end 124 | foo(x, y) 125 | ``` 126 | 127 | 请写成这样: 128 | 129 | ```@raw html 130 | 131 | ``` 132 | 133 | ```julia 134 | function foo(x::Int, y::Int) 135 | ... 136 | end 137 | foo(Int(x), Int(y)) 138 | ``` 139 | 140 | 这种风格更好,因为 `foo` 函数其实不需要接受所有类型的数,而只需要接受 `Int`。 141 | 142 | ```@raw html 143 | 145 | ``` 146 | 147 | 这里的关键在于,如果一个函数需要处理的是整数,强制让调用者来决定非整数如何被转换(比如说向下还是向上取整)会更好。同时,把类型声明得具体一些的话可以为以后的方法定义留有更多的空间。 148 | 149 | ```@raw html 150 | 153 | ``` 154 | 155 | ## 在会修改自身参数的函数名字后加 `!` 156 | 157 | ```@raw html 158 | 159 | ``` 160 | 161 | 如下的代码: 162 | 163 | ```@raw html 164 | 165 | ``` 166 | 167 | ```julia 168 | function double(a::AbstractArray{<:Number}) 169 | for i = firstindex(a):lastindex(a) 170 | a[i] *= 2 171 | end 172 | return a 173 | end 174 | ``` 175 | 176 | 请写成这样: 177 | 178 | ```@raw html 179 | 180 | ``` 181 | 182 | ```julia 183 | function double!(a::AbstractArray{<:Number}) 184 | for i = firstindex(a):lastindex(a) 185 | a[i] *= 2 186 | end 187 | return a 188 | end 189 | ``` 190 | 191 | Julia 的 Base 模块中的函数都遵循了这种规范,且包含很多例子:有的函数同时有拷贝和修改的形式(比如 [`sort`](@ref) 和 [`sort!`](@ref)),还有一些只有修改(比如 [`push!`](@ref),[`pop!`](@ref) 和 [`splice!`](@ref))。为了方便起见,这类函数通常也会把修改后的数组作为返回值。 192 | 193 | ```@raw html 194 | 198 | ``` 199 | 200 | ## 避免使用奇怪的 `Union` 类型 201 | 202 | ```@raw html 203 | 204 | ``` 205 | 206 | 使用 `Union{Function,AbstractString}` 这样的类型的时候通常意味着设计还不够清晰。 207 | 208 | ```@raw html 209 | 210 | ``` 211 | 212 | ## 避免复杂的容器类型 213 | 214 | ```@raw html 215 | 216 | ``` 217 | 218 | 像下面这样构造数组通常并没有什么好处: 219 | 220 | ```@raw html 221 | 222 | ``` 223 | 224 | ```julia 225 | a = Vector{Union{Int,AbstractString,Tuple,Array}}(undef, n) 226 | ``` 227 | 228 | 这种情况下,`Vector{Any}(undef, n)`更合适些。此外,相比将所有可能的类型都打包在一起,直接在使用时标注具体的数据类型(比如:`a[i]::Int`)对编译器来说更有用。 229 | 230 | ```@raw html 231 | 233 | ``` 234 | 235 | ## 使用和 Julia 的 `base/` 一致的命名习惯 236 | 237 | ```@raw html 238 | 239 | ``` 240 | 241 | * 模块和类型名使用大写开头的驼峰命名法:`module SparseArrays`,`struct UnitRange`。 242 | * 函数名使用小写字母,且当可读时可以将多个单词拼在一起。必要的时候,可以使用下划线作为单词分隔符。下划线也被用于指明概念的组合(比如 [`remotecall_fetch`](@ref) 作为 `fetch(remotecall(...))` 的一个更高效的实现)或者变化。 243 | * 虽然简洁性很重要,但避免使用缩写(用 [`indexin`](@ref) 而不是 `indxin`),因为这会让记住单词有没有被缩写或如何被缩写变得十分困难。 244 | 245 | ```@raw html 246 | 253 | ``` 254 | 255 | 如果一个函数名需要多个单词,请考虑这个函数是否代表了超过一个概念,是不是分成几个更小的部分更好。 256 | 257 | ```@raw html 258 | 260 | ``` 261 | 262 | ## 使用与 Julia 的 Base 模块类似的参数顺序 263 | 264 | ```@raw html 265 | 266 | ``` 267 | 268 | 一般来说,Base 库使用以下的函数参数顺序(如适用): 269 | 270 | ```@raw html 271 | 273 | ``` 274 | 275 | 1. **Function 参数**。把作为参数的函数放在第一位可以方便使用 [`do`](@ref),以传递多行匿名函数。 276 | 277 | ```@raw html 278 | 281 | ``` 282 | 283 | 2. **I/O 流**。把 `IO` 对象放在第一位,可以方便将函数传递给 [`sprint`](@ref) 之类的函数,例如 `sprint(show, x)`。 284 | 285 | ```@raw html 286 | 289 | ``` 290 | 291 | 3. **要被修改的输入**。比如,在 [`fill!(x, v)`](@ref fill!) 中,`x` 是要被修改的对象,所以放在要被插入 `x` 中的值前面。 292 | 293 | ```@raw html 294 | 297 | ``` 298 | 299 | 4. **类型**。把类型传入通常意味着要输出的值有着那种类型。在 [`parse(Int, "1")`](@ref parse) 中,类型在需要解析的字符串之前。还有很多类似的把类型放在第一位的例子,但是同时也需要注意到例如 [`read(io, String)`](@ref read) 这样的函数中,会把 `IO` 参数放在类型的更前面,这样还是保持着这里描述的顺序。 300 | 301 | ```@raw html 302 | 308 | ``` 309 | 310 | 5. **不被修改的输入**。比如在 `fill!(x, v)` 中的**不**被修改的 `v`,会放在 `x` 之后传入。 311 | 312 | ```@raw html 313 | 315 | ``` 316 | 317 | 6. **键(Key)**。对于关联集合来说,指的是键值对的键。对于其它有索引的集合来说,指的是索引。 318 | 319 | ```@raw html 320 | 323 | ``` 324 | 325 | 7. **值(Value)**。对于关联集合来说,指的是键值对的值。在类似于 `fill!(x, v)` 的情况中,指的是 `v`。 326 | 327 | ```@raw html 328 | 331 | ``` 332 | 333 | 8. **其它的所有**。任何的其它参数。 334 | 335 | ```@raw html 336 | 338 | ``` 339 | 340 | 9. **可变参数(Vararg)**。指的是在函数调用时可以被无限列在后面的参数。比如在 `Matrix{T}(uninitialized, dims)` 中,维数(dims)可以作为 [`Tuple`](@ref) 被传入(如 `Matrix{T}(uninitialized, (1,2))`),也可以作为可变参数([`Vararg`](@ref),如 `Matrix{T}(uninitialized, 1, 2)`。 341 | 342 | ```@raw html 343 | 348 | ``` 349 | 350 | 10. **关键字参数**。在 Julia 中,关键字参数本来就不得不定义在函数定义的最后,列在这里仅仅是为了完整性。 351 | 352 | ```@raw html 353 | 356 | ``` 357 | 358 | 大多数函数并不会接受上述所有种类的参数,这些数字仅仅是表示当适用时的优先权。 359 | 360 | ```@raw html 361 | 364 | ``` 365 | 366 | 当然,在一些情况下有例外。例如,[`convert`](@ref) 函数总是把类型作为第一个参数。[`setindex!`](@ref) 函数的值参数在索引参数之前,这样可以让索引作为可变参数传入。 367 | 368 | ```@raw html 369 | 373 | ``` 374 | 375 | 设计 API 时,尽可能秉承着这种一般顺序会让函数的使用者有一种更一致的体验。 376 | 377 | ```@raw html 378 | 380 | ``` 381 | 382 | ## 不要过度使用 try-catch 383 | 384 | ```@raw html 385 | 386 | ``` 387 | 388 | 比起依赖于捕获错误,更好的是避免错误。 389 | 390 | ```@raw html 391 | 392 | ``` 393 | 394 | ## 不要给条件语句加括号 395 | 396 | ```@raw html 397 | 398 | ``` 399 | 400 | Julia 不要求在 `if` 和 `while` 后的条件两边加括号。使用如下写法: 401 | 402 | ```@raw html 403 | 404 | ``` 405 | 406 | ```julia 407 | if a == b 408 | ``` 409 | 410 | 而不是: 411 | 412 | ```julia 413 | if (a == b) 414 | ``` 415 | 416 | ## 不要过度使用 `...` 417 | 418 | ```@raw html 419 | 420 | ``` 421 | 422 | 拼接函数参数是会上瘾的。请用简单的 `[a; b]` 来代替 `[a..., b...]`,因为前者已经是被拼接的数组了。[`collect(a)`](@ref) 也比 `[a...]` 更好,但因为 `a` 已经是一个可迭代的变量了,通常不把它转换成数组就直接使用甚至更好。 423 | 424 | ```@raw html 425 | 428 | ``` 429 | 430 | ## 不要使用不必要的静态参数 431 | 432 | ```@raw html 433 | 434 | ``` 435 | 436 | 如下的函数签名: 437 | 438 | ```@raw html 439 | 440 | ``` 441 | 442 | ```julia 443 | foo(x::T) where {T<:Real} = ... 444 | ``` 445 | 446 | 应当被写作: 447 | 448 | ```@raw html 449 | 450 | ``` 451 | 452 | ```julia 453 | foo(x::Real) = ... 454 | ``` 455 | 456 | 尤其是当 `T` 没有被用在函数体中时格外有意义。即使 `T` 被用到了,通常也可以被替换为 [`typeof(x)`](@ref),后者不会导致性能上的差别。注意这并不是针对静态参数的一般警告,而仅仅是针对那些不必要的情况。 457 | 458 | ```@raw html 459 | 462 | ``` 463 | 464 | 同样需要注意的是,容器类型在函数调用中可能明确地需要类型参数。详情参见[避免使用抽象容器的域](@ref)。 465 | 466 | ```@raw html 467 | 469 | ``` 470 | 471 | ## 避免判断变量是实例还是类型的混乱 472 | 473 | ```@raw html 474 | 475 | ``` 476 | 477 | 如下的一组定义容易令人困惑: 478 | 479 | ```@raw html 480 | 481 | ``` 482 | 483 | ```julia 484 | foo(::Type{MyType}) = ... 485 | foo(::MyType) = foo(MyType) 486 | ``` 487 | 488 | 请决定问题里的概念应当是 `MyType` 还是 `MyType()`,然后坚持使用其一。 489 | 490 | ```@raw html 491 | 493 | ``` 494 | 495 | 默认使用实例是比较受推崇的风格,然后只在为了解决一些问题必要时添加涉及到 `Type{MyType}` 的方法。 496 | 497 | ```@raw html 498 | 500 | ``` 501 | 502 | 如果一个类型实际上是个枚举,它应该被定义成一个单一的类型(理想的情况是不可变结构或原始类型),把枚举值作为它的实例。构造器和转换器可以检查那些值是否有效。这种设计比把枚举做成抽象类型,并把“值”做成子类型来得更受推崇。 503 | 504 | ```@raw html 505 | 509 | ``` 510 | 511 | ## 不要过度使用宏 512 | 513 | ```@raw html 514 | 515 | ``` 516 | 517 | 请注意有的宏实际上可以被写成一个函数。 518 | 519 | ```@raw html 520 | 521 | ``` 522 | 523 | 在宏内部调用 [`eval`](@ref) 是一个特别危险的警告标志,它意味着这个宏仅在被最外层调用时起作用。如果这样的宏被写成函数,它会自然地访问得到它所需要的运行时值。 524 | 525 | ```@raw html 526 | 529 | ``` 530 | 531 | ## 不要把不安全的操作暴露在接口层 532 | 533 | ```@raw html 534 | 535 | ``` 536 | 537 | 如果你有一个使用本地指针的类型: 538 | 539 | ```@raw html 540 | 541 | ``` 542 | 543 | ```julia 544 | mutable struct NativeType 545 | p::Ptr{UInt8} 546 | ... 547 | end 548 | ``` 549 | 550 | 不要定义类似如下的函数: 551 | 552 | ```@raw html 553 | 554 | ``` 555 | 556 | ```julia 557 | getindex(x::NativeType, i) = unsafe_load(x.p, i) 558 | ``` 559 | 560 | 这里的问题在于,这个类型的用户可能会在意识不到这个操作不安全的情况下写出 `x[i]`,然后容易遇到内存错误。 561 | 562 | ```@raw html 563 | 565 | ``` 566 | 567 | 在这样的函数中,可以加上对操作的检查来确保安全,或者可以在名字的某处加上 `unsafe` 来警告调用者。 568 | 569 | ```@raw html 570 | 572 | ``` 573 | 574 | ## 不要重载基础容器类型的方法 575 | 576 | ```@raw html 577 | 578 | ``` 579 | 580 | 有时可能会想要写这样的定义: 581 | 582 | ```@raw html 583 | 584 | ``` 585 | 586 | ```julia 587 | show(io::IO, v::Vector{MyType}) = ... 588 | ``` 589 | 590 | 这样可以提供对特定的某种新元素类型的向量的自定义显示。这种做法虽然很诱人,但应当被避免。这里的问题在于用户会想着一个像 `Vector()` 这样熟知的类型以某种方式表现,但过度自定义的行为会让使用变得更难。 591 | 592 | ```@raw html 593 | 596 | ``` 597 | 598 | ## 避免类型盗版 599 | 600 | ```@raw html 601 | 602 | ``` 603 | 604 | “类型盗版”(type piracy)指的是扩展或是重定义 Base 或其它包中的并不是你所定义的类型的方法。在某些情况下,你可以几乎毫无副作用地逃避类型盗版。但在极端情况下,你甚至会让 Julia 崩溃(比如说你的方法扩展或重定义造成了对 `ccall` 传入了无效的输入)。类型盗版也让代码推导变得更复杂,且可能会引入难以预料和诊断的不兼容性。 605 | 606 | ```@raw html 607 | 613 | ``` 614 | 615 | 例如,你也许想在一个模块中定义符号上的乘法: 616 | 617 | ```@raw html 618 | 619 | ``` 620 | 621 | ```julia 622 | module A 623 | import Base.* 624 | *(x::Symbol, y::Symbol) = Symbol(x,y) 625 | end 626 | ``` 627 | 628 | 这里的问题时现在其它用到 `Base.*` 的模块同样会看到这个定义。由于 `Symbol` 是定义在 Base 里再被其它模块所使用的,这可能不可预料地改变无关代码的行为。这里有几种替代的方式,包括使用一个不同的函数名称,或是把 `Symbol` 给包在另一个你自己定义的类型中。 629 | 630 | ```@raw html 631 | 635 | ``` 636 | 637 | 有时候,耦合的包可能会使用类型盗版,以此来从定义分隔特性,尤其是当那些包是一些合作的作者设计的时候,且那些定义是可重用的时候。例如,一个包可能提供一些对处理色彩有用的类型,另一个包可能为那些类型定义色彩空间之间转换的方法。再举一个例子,一个包可能是一些 C 代码的简易包装,另一个包可能就“盗版”来实现一些更高级别的、对 Julia 友好的 API。 638 | 639 | ```@raw html 640 | 647 | ``` 648 | 649 | ## 注意类型相等 650 | 651 | ```@raw html 652 | 653 | ``` 654 | 655 | 通常会用 [`isa`](@ref) 和 [`<:`](@ref) 来对类型进行测试,而不会用到 `==`。检测类型的相等通常只对和一个已知的具体类型比较有意义(例如 `T == Float64`),或者你**真的真的**知道自己在做什么。 656 | 657 | ```@raw html 658 | 661 | ``` 662 | 663 | ## 不要写 `x->f(x)` 664 | 665 | ```@raw html 666 | 667 | ``` 668 | 669 | 因为调用高阶函数时经常会用到匿名函数,很容易认为这是合理甚至必要的。但任何函数都可以被直接传递,并不需要被“包"在一个匿名函数中。比如 `map(x->f(x), a)` 应当被写成 [`map(f, a)`](@ref)。 670 | 671 | ```@raw html 672 | 675 | ``` 676 | 677 | ## 尽可能避免使用浮点数作为通用代码的字面量 678 | 679 | ```@raw html 680 | 681 | ``` 682 | 683 | 当写处理数字,且可以处理多种不同数字类型的参数的通用代码时,请使用对参数影响(通过类型提升)尽可能少的类型的字面量。 684 | 685 | ```@raw html 686 | 689 | ``` 690 | 691 | 例如, 692 | 693 | ```@raw html 694 | 695 | ``` 696 | 697 | ```jldoctest 698 | julia> f(x) = 2.0 * x 699 | f (generic function with 1 method) 700 | 701 | julia> f(1//2) 702 | 1.0 703 | 704 | julia> f(1/2) 705 | 1.0 706 | 707 | julia> f(1) 708 | 2.0 709 | ``` 710 | 711 | 而 712 | 713 | ```@raw html 714 | 715 | ``` 716 | 717 | ```jldoctest 718 | julia> g(x) = 2 * x 719 | g (generic function with 1 method) 720 | 721 | julia> g(1//2) 722 | 1//1 723 | 724 | julia> g(1/2) 725 | 1.0 726 | 727 | julia> g(1) 728 | 2 729 | ``` 730 | 731 | 如你所见,使用了 `Int` 字面量的第二个版本保留了输入参数的类型,而第一个版本没有。这是因为例如 `promote_type(Int, Float64) == Float64`,且做乘法时会需要类型提升。类似地,[`Rational`](@ref) 字面量比 [`Float64`](@ref) 字面量对类型有着更小的破坏性,但比 `Int` 大。 732 | 733 | ```@raw html 734 | 738 | ``` 739 | 740 | ```jldoctest 741 | julia> h(x) = 2//1 * x 742 | h (generic function with 1 method) 743 | 744 | julia> h(1//2) 745 | 1//1 746 | 747 | julia> h(1/2) 748 | 1.0 749 | 750 | julia> h(1) 751 | 2//1 752 | ``` 753 | 754 | 所以,可能时尽量使用 `Int` 字面量,对非整数字面量使用 `Rational{Int}`,这样可以让代码变得更容易使用。 755 | 756 | ```@raw html 757 | 759 | ``` -------------------------------------------------------------------------------- /docs/src/manual/integers-and-floating-point-numbers.md: -------------------------------------------------------------------------------- 1 | # 整数和浮点数 2 | 3 | ```@raw html 4 | 5 | ``` 6 | 7 | 整数和浮点值是算术和计算的基础。这些数值内建的表示被称作数值原始类型(numeric primitive),且整数和浮点数在代码中作为即时的值被称作数值字面量(numeric literal)。例如,`1` 是个整型字面量,`1.0` 是个浮点型字面量,它们在内存中作为对象的二进制表示就是数值原始类型。 8 | 9 | ```@raw html 10 | 15 | ``` 16 | 17 | Julia 提供了很丰富的原始数值类型,以及在它们上定义的整套的算术与按位运算符和标准数学函数。这些函数直接映射到现代计算机原生支持的数值类型及运算上,因此 Julia 可以完整地利用运算资源的优势。此外,Julia 还为[任意精度算术](@ref)提供了软件支持,从而能够处理在那些无法高效地使用原生硬件表示的数值上的运算,虽然需要以性能变得相对低一些为代价。 18 | 19 | ```@raw html 20 | 27 | ``` 28 | 29 | 以下是 Julia 的原始数值类型: 30 | 31 | * **整数类型:** 32 | 33 | ```@raw html 34 | 35 | 36 | ``` 37 | 38 | | 类型 | 带符号? | 比特数 | 最小值 | 最大值 | 39 | |:------------------|:--------|:-------|:------------|:-----------| 40 | | [`Int8`](@ref) | ✓ | 8 | -2^7 | 2^7 - 1 | 41 | | [`UInt8`](@ref) | | 8 | 0 | 2^8 - 1 | 42 | | [`Int16`](@ref) | ✓ | 16 | -2^15 | 2^15 - 1 | 43 | | [`UInt16`](@ref) | | 16 | 0 | 2^16 - 1 | 44 | | [`Int32`](@ref) | ✓ | 32 | -2^31 | 2^31 - 1 | 45 | | [`UInt32`](@ref) | | 32 | 0 | 2^32 - 1 | 46 | | [`Int64`](@ref) | ✓ | 64 | -2^63 | 2^63 - 1 | 47 | | [`UInt64`](@ref) | | 64 | 0 | 2^64 - 1 | 48 | | [`Int128`](@ref) | ✓ | 128 | -2^127 | 2^127 - 1 | 49 | | [`UInt128`](@ref) | | 128 | 0 | 2^128 - 1 | 50 | | [`Bool`](@ref) | N/A | 8 | `false` (0) | `true` (1) | 51 | 52 | 53 | ```@raw html 54 | 69 | ``` 70 | 71 | * **浮点类型:** 72 | 73 | 74 | | 类型 | 精度 | 比特数 | 75 | |:------------------|:-------------------------------------------------------------------------------|:-------| 76 | | [`Float16`](@ref) | [half](https://en.wikipedia.org/wiki/Half-precision_floating-point_format) | 16 | 77 | | [`Float32`](@ref) | [single](https://en.wikipedia.org/wiki/Single_precision_floating-point_format) | 32 | 78 | | [`Float64`](@ref) | [double](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) | 64 | 79 | 80 | 81 | ```@raw html 82 | 83 | 84 | 91 | ``` 92 | 93 | 此外,对[复数和分数](@ref)的完整支持是在这些原始类型之上建立起来的。多亏了 Julia 有一个很灵活的、用户可扩展的[类型提升系统](@ref conversion-and-promotion),所有的数值类型都无需现实转换就可以很自然地相互进行运算。 94 | 95 | ```@raw html 96 | 99 | ``` 100 | 101 | ## 整数 102 | 103 | ```@raw html 104 | 105 | ``` 106 | 107 | 字面的整数以标准习俗表示: 108 | 109 | ```@raw html 110 | 111 | ``` 112 | 113 | ```jldoctest 114 | julia> 1 115 | 1 116 | 117 | julia> 1234 118 | 1234 119 | ``` 120 | 121 | 整型字面量的默认类型决定于目标系统是 32 位架构还是 64 位的: 122 | 123 | ```@raw html 124 | 126 | ``` 127 | 128 | ```julia-repl 129 | # 32-bit system: 130 | julia> typeof(1) 131 | Int32 132 | 133 | # 64-bit system: 134 | julia> typeof(1) 135 | Int64 136 | ``` 137 | 138 | Julia 的内部变量 [`Sys.WORD_SIZE`](@ref) 指示了目标系统是 32 位还是 64 位: 139 | 140 | ```@raw html 141 | 143 | ``` 144 | 145 | ```julia-repl 146 | # 32-bit system: 147 | julia> Sys.WORD_SIZE 148 | 32 149 | 150 | # 64-bit system: 151 | julia> Sys.WORD_SIZE 152 | 64 153 | ``` 154 | 155 | Julia 也定义了 `Int` 与 `UInt` 类型,它们分别是系统有符号和无符号的原生整数类型的别名。 156 | 157 | ```@raw html 158 | 160 | ``` 161 | 162 | ```julia-repl 163 | # 32-bit system: 164 | julia> Int 165 | Int32 166 | julia> UInt 167 | UInt32 168 | 169 | # 64-bit system: 170 | julia> Int 171 | Int64 172 | julia> UInt 173 | UInt64 174 | ``` 175 | 176 | 那些超过 32 位表示的大整数,如果能用 64 位表示,则无论是什么系统都会用 64 位表示: 177 | 178 | ```@raw html 179 | 181 | ``` 182 | 183 | ```jldoctest 184 | # 32-bit or 64-bit system: 185 | julia> typeof(3000000000) 186 | Int64 187 | ``` 188 | 189 | 无符号整数通过 `0x` 前缀以及十六进制数 `0-9a-f` 输入和输出(输入也可以使用大写的 `A-F`)。无符号值的位数决定于使用的十六进制数字的数量: 190 | 191 | ```@raw html 192 | 195 | ``` 196 | 197 | ```jldoctest 198 | julia> 0x1 199 | 0x01 200 | 201 | julia> typeof(ans) 202 | UInt8 203 | 204 | julia> 0x123 205 | 0x0123 206 | 207 | julia> typeof(ans) 208 | UInt16 209 | 210 | julia> 0x1234567 211 | 0x01234567 212 | 213 | julia> typeof(ans) 214 | UInt32 215 | 216 | julia> 0x123456789abcdef 217 | 0x0123456789abcdef 218 | 219 | julia> typeof(ans) 220 | UInt64 221 | 222 | julia> 0x11112222333344445555666677778888 223 | 0x11112222333344445555666677778888 224 | 225 | julia> typeof(ans) 226 | UInt128 227 | ``` 228 | 229 | 这种做法是由于当人们使用无符号十六进制字面量表示整数值,通常会用它们来表示一个固定的数值字节序列,而不仅仅是个整数值。 230 | 231 | ```@raw html 232 | 235 | ``` 236 | 237 | 还记得这个 [`ans`](@ref) 吗?它表示交互式会话中上一个表达式的运算结果,但是在其他方式运行的 Julia 代码不存在。 238 | 239 | ```@raw html 240 | 242 | ``` 243 | 244 | 二进制和八进制字面量也受到支持: 245 | 246 | ```@raw html 247 | 248 | ``` 249 | 250 | ```jldoctest 251 | julia> 0b10 252 | 0x02 253 | 254 | julia> typeof(ans) 255 | UInt8 256 | 257 | julia> 0o010 258 | 0x08 259 | 260 | julia> typeof(ans) 261 | UInt8 262 | 263 | julia> 0x00000000000000001111222233334444 264 | 0x00000000000000001111222233334444 265 | 266 | julia> typeof(ans) 267 | UInt128 268 | ``` 269 | 270 | 十六进制、二进制和八进制的字面量都会产生无符号的整数类型。当字面量不是开头全是 0 时,它们二进制数据项的位数会是最少需要的位数。当开头都是 0 时,位数决定于一个字面量的最少需要位数,这里的字面量指的是一个有着同样长度但开头都为 `1` 的数。这样用户就可以控制位数了。那些无法使用 `UInt128` 类型存储下的值无法写成这样的字面量。 271 | 272 | ```@raw html 273 | 279 | ``` 280 | 281 | 二进制、八进制和十六进制的字面量可以在前面紧接着加一个 `-` 符号,这样可以产生一个和原字面量有着同样位数而值为原数的补码(二补数): 282 | 283 | ```@raw html 284 | 287 | ``` 288 | 289 | ```jldoctest 290 | julia> -0x2 291 | 0xfe 292 | 293 | julia> -0x0002 294 | 0xfffe 295 | ``` 296 | 297 | 整型等原始数值类型的最小和最大可表示的值可用 [`typemin`](@ref) 和 [`typemax`](@ref) 函数得到: 298 | 299 | ```@raw html 300 | 302 | ``` 303 | 304 | ```jldoctest 305 | julia> (typemin(Int32), typemax(Int32)) 306 | (-2147483648, 2147483647) 307 | 308 | julia> for T in [Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128] 309 | println("$(lpad(T,7)): [$(typemin(T)),$(typemax(T))]") 310 | end 311 | Int8: [-128,127] 312 | Int16: [-32768,32767] 313 | Int32: [-2147483648,2147483647] 314 | Int64: [-9223372036854775808,9223372036854775807] 315 | Int128: [-170141183460469231731687303715884105728,170141183460469231731687303715884105727] 316 | UInt8: [0,255] 317 | UInt16: [0,65535] 318 | UInt32: [0,4294967295] 319 | UInt64: [0,18446744073709551615] 320 | UInt128: [0,340282366920938463463374607431768211455] 321 | ``` 322 | 323 | [`typemin`](@ref) 和 [`typemax`](@ref) 返回的值总是属于所给的参数类型。(上面的表达式用了一些我们目前还没有介绍的功能,包括 [for 循环](@ref man-loops)、[字符串](@ref man-strings)和[插值](@ref),但对于已有一些编程经验的用户应该是足够容易理解的。) 324 | 325 | ```@raw html 326 | 330 | ``` 331 | 332 | ### 溢出 333 | 334 | ```@raw html 335 | 336 | ``` 337 | 338 | Julia 中,超过了一个类型最大可表示的值时会以一个环绕行为(wraparound behavior)给出结果: 339 | 340 | ```@raw html 341 | 342 | ``` 343 | 344 | ```jldoctest 345 | julia> x = typemax(Int64) 346 | 9223372036854775807 347 | 348 | julia> x + 1 349 | -9223372036854775808 350 | 351 | julia> x + 1 == typemin(Int64) 352 | true 353 | ``` 354 | 355 | 因此,Julia 整数的算术实际上是[模算数](https://zh.wikipedia.org/wiki/%E6%A8%A1%E7%AE%97%E6%95%B8)的一种形式。它可以反映出如现代计算机所实现的一样的整数算术的特点。在可能遇到溢出的应用场景中,对溢出产生的环绕行为进行显式的检查是很重要的。否则,推荐使用[任意精度算术](@ref)中的 [`BigInt`](@ref) 类型作为替代。 356 | 357 | ```@raw html 358 | 363 | ``` 364 | 365 | ### 除法错误 366 | 367 | ```@raw html 368 | 369 | ``` 370 | 371 | 整数除法(`div` 函数)有两种异常情况:被 0 除,以及使用 -1 去除最小的负数([`typemin`](@ref))。这两种情况都会抛出一个 [`DivideError`](@ref) 错误。取余和取模函数(`rem` 和 `mod`)在它们第二个参数是零时抛出 [`DivideError`](@ref) 错误。 372 | 373 | ```@raw html 374 | 378 | ``` 379 | 380 | ## 浮点数 381 | 382 | ```@raw html 383 | 384 | ``` 385 | 386 | 字面的浮点数也使用标准习俗表示,必要时可使用 [E-表示法](https://en.wikipedia.org/wiki/Scientific_notation#E-notation): 387 | 388 | ```@raw html 389 | 391 | ``` 392 | 393 | ```jldoctest 394 | julia> 1.0 395 | 1.0 396 | 397 | julia> 1. 398 | 1.0 399 | 400 | julia> 0.5 401 | 0.5 402 | 403 | julia> .5 404 | 0.5 405 | 406 | julia> -1.23 407 | -1.23 408 | 409 | julia> 1e10 410 | 1.0e10 411 | 412 | julia> 2.5e-4 413 | 0.00025 414 | ``` 415 | 416 | 上面的结果都是 [`Float64`](@ref) 值。使用 `f` 替代 `e` 可以写出字面的 [`Float32`](@ref) 值: 417 | 418 | ```@raw html 419 | 421 | ``` 422 | 423 | ```jldoctest 424 | julia> 0.5f0 425 | 0.5f0 426 | 427 | julia> typeof(ans) 428 | Float32 429 | 430 | julia> 2.5f-4 431 | 0.00025f0 432 | ``` 433 | 434 | 值也可以很容易地被转换成 [`Float32`](@ref): 435 | 436 | ```@raw html 437 | 438 | ``` 439 | 440 | ```jldoctest 441 | julia> Float32(-1.5) 442 | -1.5f0 443 | 444 | julia> typeof(ans) 445 | Float32 446 | ``` 447 | 448 | 也存在十六进制的浮点数字面量,但只适用于 [`Float64`] 值,加上使用 `p` 及以 2 为底的指数来表示: 449 | 450 | ```@raw html 451 | 453 | ``` 454 | 455 | ```jldoctest 456 | julia> 0x1p0 457 | 1.0 458 | 459 | julia> 0x1.8p3 460 | 12.0 461 | 462 | julia> 0x.4p-1 463 | 0.125 464 | 465 | julia> typeof(ans) 466 | Float64 467 | ``` 468 | 469 | Julia 也支持半精度浮点数([`Float16`](@ref)),但它们是由软件实现的,且使用 [`Float32`](@ref) 做计算。 470 | 471 | ```@raw html 472 | 474 | ``` 475 | 476 | ```jldoctest 477 | julia> sizeof(Float16(4.)) 478 | 2 479 | 480 | julia> 2*Float16(4.) 481 | Float16(8.0) 482 | ``` 483 | 484 | 下划线 `_` 可被用作数字分隔符: 485 | 486 | ```@raw html 487 | 488 | ``` 489 | 490 | ```jldoctest 491 | julia> 10_000, 0.000_000_005, 0xdead_beef, 0b1011_0010 492 | (10000, 5.0e-9, 0xdeadbeef, 0xb2) 493 | ``` 494 | 495 | ### 浮点型的零 496 | 497 | ```@raw html 498 | 499 | ``` 500 | 501 | 浮点数有[两个零](https://zh.wikipedia.org/wiki/%E2%88%920),正零和负零。它们相互相等但有着不同的二进制表示,可以使用 `bits` 函数来查看: 502 | 503 | ```@raw html 504 | 507 | ``` 508 | 509 | ```jldoctest 510 | julia> 0.0 == -0.0 511 | true 512 | 513 | julia> bitstring(0.0) 514 | "0000000000000000000000000000000000000000000000000000000000000000" 515 | 516 | julia> bitstring(-0.0) 517 | "1000000000000000000000000000000000000000000000000000000000000000" 518 | ``` 519 | 520 | ### 特殊的浮点值 521 | 522 | ```@raw html 523 | 524 | ``` 525 | 526 | 有三种特定的标准浮点值不和实数轴上任何一点对应: 527 | 528 | ```@raw html 529 | 531 | ``` 532 | 533 | | `Float16` | `Float32` | `Float64` | 名称 | 描述 | 534 | |:----------|:----------|:----------|:-----------------------|:-----------------------------------------------| 535 | | `Inf16` | `Inf32` | `Inf` | 正无穷大 | 一个比所有有限浮点值都更大的值 | 536 | | `-Inf16` | `-Inf32` | `-Inf` | 负无穷大 | 一个比所有有限浮点值都更小的值 | 537 | | `NaN16` | `NaN32` | `NaN` | 不是数(not a number) | 一个不和任何浮点值(包括自己)相等(`==`)的值 | 538 | 539 | 540 | ```@raw html 541 | 548 | ``` 549 | 550 | 对于这些非有限浮点值相互之间以及关于其它浮点值的顺序的更多讨论,请参见[数值比较](Wref)。根据 [IEEE 754 标准](https://en.wikipedia.org/wiki/IEEE_754_revision),这些浮点值是某些算术运算的结果: 551 | 552 | ```@raw html 553 | 556 | ``` 557 | 558 | ```jldoctest 559 | julia> 1/Inf 560 | 0.0 561 | 562 | julia> 1/0 563 | Inf 564 | 565 | julia> -5/0 566 | -Inf 567 | 568 | julia> 0.000001/0 569 | Inf 570 | 571 | julia> 0/0 572 | NaN 573 | 574 | julia> 500 + Inf 575 | Inf 576 | 577 | julia> 500 - Inf 578 | -Inf 579 | 580 | julia> Inf + Inf 581 | Inf 582 | 583 | julia> Inf - Inf 584 | NaN 585 | 586 | julia> Inf * Inf 587 | Inf 588 | 589 | julia> Inf / Inf 590 | NaN 591 | 592 | julia> 0 * Inf 593 | NaN 594 | ``` 595 | 596 | [`typemin`](@ref) 和 [`typemax`](@ref) 函数同样适用于浮点类型: 597 | 598 | ```@raw html 599 | 600 | ``` 601 | 602 | ```jldoctest 603 | julia> (typemin(Float16),typemax(Float16)) 604 | (-Inf16, Inf16) 605 | 606 | julia> (typemin(Float32),typemax(Float32)) 607 | (-Inf32, Inf32) 608 | 609 | julia> (typemin(Float64),typemax(Float64)) 610 | (-Inf, Inf) 611 | ``` 612 | 613 | ### 机器零点(Machine epsilon) 614 | 615 | ```@raw html 616 | 617 | ``` 618 | 619 | 大多数实数都无法用浮点数准确地表示,因此有必要知道两个相邻可表示的浮点数间的距离。它通常被叫做[机器零点](https://en.wikipedia.org/wiki/Machine_epsilon)。 620 | 621 | ```@raw html 622 | 625 | ``` 626 | 627 | Julia 提供了 [`eps`](@ref) 函数,它可以给出 `1.0` 与下一个更大的可表示的浮点数之间的距离: 628 | 629 | ```@raw html 630 | 632 | ``` 633 | 634 | ```jldoctest 635 | julia> eps(Float32) 636 | 1.1920929f-7 637 | 638 | julia> eps(Float64) 639 | 2.220446049250313e-16 640 | 641 | julia> eps() # same as eps(Float64) 642 | 2.220446049250313e-16 643 | ``` 644 | 645 | 这些值分别是 [`Float32`](@ref) 中的 `2.0^-23` 和 [`Float64`](@ref) 中的 `2.0^-52`。[`eps`](@ref) 函数也可以接受一个浮点值作为参数,然后给出这个值与下一个可表示的值直接的绝对差。也就是说,`eps(x)` 产生一个和 `x` 类型相同的值使得 `x + eps(x)` 是比 `x` 更大的下一个可表示的浮点值: 646 | 647 | 648 | ```@raw html 649 | 654 | ``` 655 | 656 | ```jldoctest 657 | julia> eps(1.0) 658 | 2.220446049250313e-16 659 | 660 | julia> eps(1000.) 661 | 1.1368683772161603e-13 662 | 663 | julia> eps(1e-27) 664 | 1.793662034335766e-43 665 | 666 | julia> eps(0.0) 667 | 5.0e-324 668 | ``` 669 | 670 | 两个相邻可表示的浮点数之间的距离并不是常数,数值越小,间距越小,数值越大,间距越大。换句话说,可表示的浮点数在实数轴上的零点附近最稠密,并沿着远离零点的方向以指数型的速度变得越来越稀疏。根据定义,`eps(1.0)` 与 `eps(Float64)` 相等,因为 `1.0` 是个 64 位浮点值。 671 | 672 | ```@raw html 673 | 678 | ``` 679 | 680 | Julia 也提供了 [`nextfloat`](@ref) 和 [`prevfloat`](@ref) 两个函数分别来返回对于参数下一个更大或更小的可表示的浮点数: 681 | 682 | ```@raw html 683 | 685 | ``` 686 | 687 | ```jldoctest 688 | julia> x = 1.25f0 689 | 1.25f0 690 | 691 | julia> nextfloat(x) 692 | 1.2500001f0 693 | 694 | julia> prevfloat(x) 695 | 1.2499999f0 696 | 697 | julia> bitstring(prevfloat(x)) 698 | "00111111100111111111111111111111" 699 | 700 | julia> bitstring(x) 701 | "00111111101000000000000000000000" 702 | 703 | julia> bitstring(nextfloat(x)) 704 | "00111111101000000000000000000001" 705 | ``` 706 | 707 | 这个例子体现了一般原则,即相邻可表示的浮点数也有着相邻的二进制整数表示。 708 | 709 | ```@raw html 710 | 712 | ``` 713 | 714 | ### 舍入模式 715 | 716 | ```@raw html 717 | 718 | ``` 719 | 720 | 一个数如果没有精确的浮点表示,就必须被舍入到一个合适的可表示的值。然而,如果想的话,可以根据舍入模式改变舍入的方式,如 [IEEE 754 标准](https://en.wikipedia.org/wiki/IEEE_754_revision)所述。 721 | 722 | ```@raw html 723 | 727 | ``` 728 | 729 | Julia 所使用的默认模式总是 [`RoundNearest`](@ref),指的是会舍入到最接近的可表示的值,这个被舍入的值会使用尽量少的有效位数。 730 | 731 | ```@raw html 732 | 734 | ``` 735 | 736 | ### 背景及参考 737 | 738 | ```@raw html 739 | 740 | ``` 741 | 742 | 浮点算术带来了很多微妙之处,它们可能对于那些不熟悉底层实现细节的用户会是很出人意料的。然而,这些微妙之处在大部分科学计算的书籍中以及以下的参考资料中都有详细介绍: 743 | 744 | ```@raw html 745 | 748 | ``` 749 | 750 | * 浮点算术的权威性指南是 [IEEE 754-2008 Standard](http://standards.ieee.org/findstds/standard/754-2008.html)。然而在网上无法免费获得。 751 | * 关于浮点数是如何表示的,想要一个简单而明白的介绍的话,可以看 John D. Cook 在这个主题上的的[文章](https://www.johndcook.com/blog/2009/04/06/anatomy-of-a-floating-point-number/),以及他关于从这种表示与实数理想的抽象化的差别中产生的一些问题的[介绍](https://www.johndcook.com/blog/2009/04/06/numbers-are-a-leaky-abstraction/)。 752 | * 同样推荐 Bruce Dawson 的[一系列关于浮点数的博客文章](https://randomascii.wordpress.com/2012/05/20/thats-not-normalthe-performance-of-odd-floats)。 753 | * 想要一个对浮点数和使用浮点数计算时产生的数值精度问题的极好的、有深度的讨论,可以参见 David Goldberg 的文章 [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.22.6768&rep=rep1&type=pdf)。 754 | * 更多延伸文档,包括浮点数的历史、基础理论、问题以及数值计算中很多其它主题的讨论,可以参见 [William Kahan](https://en.wikipedia.org/wiki/William_Kahan) 的[写作集](https://people.eecs.berkeley.edu/~wkahan/)。他以“浮点数之父”闻名。特别感兴趣的话可以看 [An Interview with the Old Man of Floating-Point](https://people.eecs.berkeley.edu/~wkahan/ieee754status/754story.html)。 755 | 756 | 757 | ```@raw html 758 | 774 | ``` 775 | 776 | ## 任意精度算术 777 | 778 | ```@raw html 779 | 780 | ``` 781 | 782 | 为了允许使用任意精度的整数与浮点数,Julia 分别包装了 [GNU Multiple Precision Arithmetic Library (GMP)](https://gmplib.org) 以及 [GNU MPFR Library](http://www.mpfr.org)。Julia 中的 [`BigInt`](@ref) 与 [`BigFloat`](@ref) 两种类型分别提供了任意精度的整数和浮点数。 783 | 784 | ```@raw html 785 | 789 | ``` 790 | 791 | 存在从原始数字类型创建它们的构造器,也可以使用 [`parse`](@ref) 从 `AbstractString` 来构造它们。一旦被创建,它们就可以像所有其它数值类型一样参与算术(也是多亏了 Julia 的[类型提升和转换机制](@ref conversion-and-promotion))。 792 | 793 | ```@raw html 794 | 797 | ``` 798 | 799 | ```jldoctest 800 | julia> BigInt(typemax(Int64)) + 1 801 | 9223372036854775808 802 | 803 | julia> parse(BigInt, "123456789012345678901234567890") + 1 804 | 123456789012345678901234567891 805 | 806 | julia> parse(BigFloat, "1.23456789012345678901") 807 | 1.234567890123456789010000000000000000000000000000000000000000000000000000000004 808 | 809 | julia> BigFloat(2.0^66) / 3 810 | 2.459565876494606882133333333333333333333333333333333333333333333333333333333344e+19 811 | 812 | julia> factorial(BigInt(40)) 813 | 815915283247897734345611269596115894272000000000 814 | ``` 815 | 816 | 然而,上面的原始类型与 [`BigInt`](@ref)/[`BigFloat`](@ref) 之间的类型提升并不是自动的,需要明确地指定: 817 | 818 | ```@raw html 819 | 821 | ``` 822 | 823 | ```jldoctest 824 | julia> x = typemin(Int64) 825 | -9223372036854775808 826 | 827 | julia> x = x - 1 828 | 9223372036854775807 829 | 830 | julia> typeof(x) 831 | Int64 832 | 833 | julia> y = BigInt(typemin(Int64)) 834 | -9223372036854775808 835 | 836 | julia> y = y - 1 837 | -9223372036854775809 838 | 839 | julia> typeof(y) 840 | BigInt 841 | ``` 842 | 843 | [`BigFloat`](@ref) 的默认精度(有效数字的位数)和舍入模式可以通过调用 [`setprecision`](@ref) 和 [`setrounding`](@ref) 来全局地改变,所有之后的计算都会根据这些改变进行。还有一种方法,可以使用同样的函数以及 `do` 语句块来只在运行一个特定代码块时改变精度和舍入模式: 844 | 845 | ```@raw html 846 | 851 | ``` 852 | 853 | ```jldoctest 854 | julia> setrounding(BigFloat, RoundUp) do 855 | BigFloat(1) + parse(BigFloat, "0.1") 856 | end 857 | 1.100000000000000000000000000000000000000000000000000000000000000000000000000003 858 | 859 | julia> setrounding(BigFloat, RoundDown) do 860 | BigFloat(1) + parse(BigFloat, "0.1") 861 | end 862 | 1.099999999999999999999999999999999999999999999999999999999999999999999999999986 863 | 864 | julia> setprecision(40) do 865 | BigFloat(1) + parse(BigFloat, "0.1") 866 | end 867 | 1.1000000000004 868 | ``` 869 | 870 | ## [数值字面量系数](@id man-numeric-literal-coefficients) 871 | 872 | ```@raw html 873 | 874 | ``` 875 | 876 | 为了让常见的数值公式和表达式更清楚,Julia 允许变量直接跟在一个数值字面量后,暗指乘法。这可以让写多项式变得很清楚: 877 | 878 | ```@raw html 879 | 882 | ``` 883 | 884 | ```jldoctest numeric-coefficients 885 | julia> x = 3 886 | 3 887 | 888 | julia> 2x^2 - 3x + 1 889 | 10 890 | 891 | julia> 1.5x^2 - .5x + 1 892 | 13.0 893 | ``` 894 | 895 | 也会让写指数函数更加优雅: 896 | 897 | ```@raw html 898 | 899 | ``` 900 | 901 | ```jldoctest numeric-coefficients 902 | julia> 2^2x 903 | 64 904 | ``` 905 | 906 | 数值字面量系数的优先级跟一元运算符相同,比如说取相反数。所以 `2^3x` 会被解析成 `2^(3x)`,而 `2x^3` 会被解析成 `2*(x^3)`。 907 | 908 | ```@raw html 909 | 915 | ``` 916 | 917 | 数值字面量也能作为被括号表达式的系数: 918 | 919 | ```@raw html 920 | 921 | ``` 922 | 923 | ```jldoctest numeric-coefficients 924 | julia> 2(x-1)^2 - 3(x-1) + 1 925 | 3 926 | ``` 927 | !!! 注意 928 | 用于隐式乘法的数值字面量系数的优先级高于其它的二元运算符,例如乘法(`*`)和除法(`/`、`\` 以及 `//`)。这意味着,比如说,`1 / 2im` 等于 `-0.5im` 以及 `6 // 2(2+1)` 等于 `1 // 1`。 929 | 930 | ```@raw html 931 | 938 | ``` 939 | 940 | 此外,括号表达式可以被用作变量的系数,暗指表达式与变量相乘: 941 | 942 | ```@raw html 943 | 945 | ``` 946 | 947 | ```jldoctest numeric-coefficients 948 | julia> (x-1)x 949 | 6 950 | ``` 951 | 952 | 但是,无论是把两个括号表达式并列,还是把变量放在括号表达式之前,都不会被用作暗指乘法: 953 | 954 | ```@raw html 955 | 957 | ``` 958 | 959 | ```jldoctest numeric-coefficients 960 | julia> (x-1)(x+1) 961 | ERROR: MethodError: objects of type Int64 are not callable 962 | 963 | julia> x(x+1) 964 | ERROR: MethodError: objects of type Int64 are not callable 965 | ``` 966 | 967 | 这两种表达式都会被解释成函数调用:所有不是数值字面量的表达式,后面紧跟一个括号,就会被解释成使用括号内的值来调用函数(更多关于函数的信息请参见[函数](@ref))。因此,在这两种情况中,都会因为左手边的值并不是函数而产生错误 968 | 969 | ```@raw html 970 | 974 | ``` 975 | 976 | 上述的语法糖显著地降低了在写通常的数学公式时的视觉噪音。注意数值字面量系数和后面用来相乘的标识符或括号表达式之间不能有空格。 977 | 978 | ```@raw html 979 | 982 | ``` 983 | 984 | ### 语法冲突 985 | 986 | ```@raw html 987 | 988 | ``` 989 | 990 | 并列的字面量系数语法可能和两种数值字面量语法产生冲突:十六进制整数字面量以及浮点字面量的工程表示法。下面是几种会产生语法冲突的情况: 991 | 992 | ```@raw html 993 | 996 | ``` 997 | 998 | * 十六进制整数字面量 `0xff` 可能被解释成数值字面量 `0` 乘以变量 `xff`。 999 | * 浮点字面量表达式 `1e10` 可以被解释成 `1` 乘以变量 `e10`,与之等价的 `E` 形式也存在类似的情况。 1000 | * 32比特的浮点数字面量 `1.5f22` 被解释成数值 `1.5` 乘以变量 `f22` 1001 | 1002 | ```@raw html 1003 | 1011 | ``` 1012 | 1013 | 在这两种情况中,都使用这样的解释方法来解决二义性: 1014 | 1015 | ```@raw html 1016 | 1017 | ``` 1018 | 1019 | * `0x` 开头的表达式总是十六进制字面量。 1020 | * 数值开头跟着 `e` 和 `E` 的表达式总是浮点字面量。 1021 | * 数值开头跟着 `f` 的表达式总是32比特浮点字面量。 1022 | 1023 | ```@raw html 1024 | 1029 | ``` 1030 | 1031 | 由于历史原因 `E` 和 `e` 在数值字面量上是等价的,与之不同的是,`F` 只是一个行为和 `f` 不同的字母。因此开头为 `F` 的表达式将会被 1032 | 解析为一个数值字面量乘以一个变量,例如 `1.5F22`等价于 `1.5 * F22`。 1033 | 1034 | ```@raw html 1035 | 1039 | ``` 1040 | 1041 | ## 零和一的字面量 1042 | 1043 | ```@raw html 1044 | 1045 | ``` 1046 | 1047 | Julia 提供了 0 和 1 的字面量函数,可以返回特定类型或所给变量的类型。 1048 | 1049 | ```@raw html 1050 | 1052 | ``` 1053 | 1054 | | 函数 | 描述 | 1055 | |:------------------|:------------------------------------| 1056 | | [`zero(x)`](@ref) | `x` 类型或变量 `x` 的类型的零字面量 | 1057 | | [`one(x)`](@ref) | `x` 类型或变量 `x` 的类型的一字面量 | 1058 | 1059 | ```@raw html 1060 | 1066 | ``` 1067 | 1068 | 这些函数在[数值比较](@ref)中可以用来避免不必要的[类型转换](@ref conversion-and-promotion)带来的开销。 1069 | 1070 | ```@raw html 1071 | 1073 | ``` 1074 | 1075 | 例如: 1076 | 1077 | ```@raw html 1078 | 1079 | ``` 1080 | 1081 | ```jldoctest 1082 | julia> zero(Float32) 1083 | 0.0f0 1084 | 1085 | julia> zero(1.0) 1086 | 0.0 1087 | 1088 | julia> one(Int32) 1089 | 1 1090 | 1091 | julia> one(BigFloat) 1092 | 1.0 1093 | ``` 1094 | --------------------------------------------------------------------------------