165 lines
39 KiB
HTML
165 lines
39 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><title>Mathematical Operations and Elementary Functions · The Julia Language</title><script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
|
||
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
|
||
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
|
||
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
|
||
|
||
ga('create', 'UA-28835595-6', 'auto');
|
||
ga('send', 'pageview');
|
||
</script><link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.2.0/normalize.min.css" rel="stylesheet" type="text/css"/><link href="https://fonts.googleapis.com/css?family=Lato|Roboto+Mono" rel="stylesheet" type="text/css"/><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css"/><link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/default.min.css" rel="stylesheet" type="text/css"/><script>documenterBaseURL=".."</script><script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.2.0/require.min.js" data-main="../assets/documenter.js"></script><script src="../siteinfo.js"></script><script src="../../versions.js"></script><link href="../assets/documenter.css" rel="stylesheet" type="text/css"/><link href="../assets/julia-manual.css" rel="stylesheet" type="text/css"/></head><body><nav class="toc"><a href="../index.html"><img class="logo" src="../assets/logo.png" alt="The Julia Language logo"/></a><h1>The Julia Language</h1><select id="version-selector" onChange="window.location.href=this.value" style="visibility: hidden"></select><form class="search" id="search-form" action="../search.html"><input id="search-query" name="q" type="text" placeholder="Search docs"/></form><ul><li><a class="toctext" href="../index.html">Home</a></li><li><span class="toctext">Manual</span><ul><li><a class="toctext" href="introduction.html">Introduction</a></li><li><a class="toctext" href="getting-started.html">Getting Started</a></li><li><a class="toctext" href="variables.html">Variables</a></li><li><a class="toctext" href="integers-and-floating-point-numbers.html">Integers and Floating-Point Numbers</a></li><li class="current"><a class="toctext" href="mathematical-operations.html">Mathematical Operations and Elementary Functions</a><ul class="internal"><li><a class="toctext" href="#Arithmetic-Operators-1">Arithmetic Operators</a></li><li><a class="toctext" href="#Bitwise-Operators-1">Bitwise Operators</a></li><li><a class="toctext" href="#Updating-operators-1">Updating operators</a></li><li><a class="toctext" href="#man-dot-operators-1">Vectorized "dot" operators</a></li><li><a class="toctext" href="#Numeric-Comparisons-1">Numeric Comparisons</a></li><li><a class="toctext" href="#Operator-Precedence-1">Operator Precedence</a></li><li><a class="toctext" href="#Numerical-Conversions-1">Numerical Conversions</a></li></ul></li><li><a class="toctext" href="complex-and-rational-numbers.html">Complex and Rational Numbers</a></li><li><a class="toctext" href="strings.html">Strings</a></li><li><a class="toctext" href="functions.html">Functions</a></li><li><a class="toctext" href="control-flow.html">Control Flow</a></li><li><a class="toctext" href="variables-and-scoping.html">Scope of Variables</a></li><li><a class="toctext" href="types.html">Types</a></li><li><a class="toctext" href="methods.html">Methods</a></li><li><a class="toctext" href="constructors.html">Constructors</a></li><li><a class="toctext" href="conversion-and-promotion.html">Conversion and Promotion</a></li><li><a class="toctext" href="interfaces.html">Interfaces</a></li><li><a class="toctext" href="modules.html">Modules</a></li><li><a class="toctext" href="documentation.html">Documentation</a></li><li><a class="toctext" href="metaprogramming.html">Metaprogramming</a></li><li><a class="toctext" href="arrays.html">Multi-dimensional Arrays</a></li><li><a class="toctext" href="linear-algebra.html">Linear algebra</a></li><li><a class="toctext" href="networking-and-streams.html">Networking and Streams</a></li><li><a class="toctext" href="parallel-computing.html">Parallel Computing</a></li><li><a class="toctext" href="dates.html">Date and DateTime</a></li><li><a class="toctext" href="interacting-with-julia.html">Interacting With Julia</a></li><li><a class="toctext" href="running-external-programs.html">Running External Programs</a></li><li><a class="toctext" href="calling-c-and-fortran-code.html">Calling C and Fortran Code</a></li><li><a class="toctext" href="handling-operating-system-variation.html">Handling Operating System Variation</a></li><li><a class="toctext" href="environment-variables.html">Environment Variables</a></li><li><a class="toctext" href="embedding.html">Embedding Julia</a></li><li><a class="toctext" href="packages.html">Packages</a></li><li><a class="toctext" href="profile.html">Profiling</a></li><li><a class="toctext" href="stacktraces.html">Stack Traces</a></li><li><a class="toctext" href="performance-tips.html">Performance Tips</a></li><li><a class="toctext" href="workflow-tips.html">Workflow Tips</a></li><li><a class="toctext" href="style-guide.html">Style Guide</a></li><li><a class="toctext" href="faq.html">Frequently Asked Questions</a></li><li><a class="toctext" href="noteworthy-differences.html">Noteworthy Differences from other Languages</a></li><li><a class="toctext" href="unicode-input.html">Unicode Input</a></li></ul></li><li><span class="toctext">Standard Library</span><ul><li><a class="toctext" href="../stdlib/base.html">Essentials</a></li><li><a class="toctext" href="../stdlib/collections.html">Collections and Data Structures</a></li><li><a class="toctext" href="../stdlib/math.html">Mathematics</a></li><li><a class="toctext" href="../stdlib/numbers.html">Numbers</a></li><li><a class="toctext" href="../stdlib/strings.html">Strings</a></li><li><a class="toctext" href="../stdlib/arrays.html">Arrays</a></li><li><a class="toctext" href="../stdlib/parallel.html">Tasks and Parallel Computing</a></li><li><a class="toctext" href="../stdlib/linalg.html">Linear Algebra</a></li><li><a class="toctext" href="../stdlib/constants.html">Constants</a></li><li><a class="toctext" href="../stdlib/file.html">Filesystem</a></li><li><a class="toctext" href="../stdlib/io-network.html">I/O and Network</a></li><li><a class="toctext" href="../stdlib/punctuation.html">Punctuation</a></li><li><a class="toctext" href="../stdlib/sort.html">Sorting and Related Functions</a></li><li><a class="toctext" href="../stdlib/pkg.html">Package Manager Functions</a></li><li><a class="toctext" href="../stdlib/dates.html">Dates and Time</a></li><li><a class="toctext" href="../stdlib/iterators.html">Iteration utilities</a></li><li><a class="toctext" href="../stdlib/test.html">Unit Testing</a></li><li><a class="toctext" href="../stdlib/c.html">C Interface</a></li><li><a class="toctext" href="../stdlib/libc.html">C Standard Library</a></li><li><a class="toctext" href="../stdlib/libdl.html">Dynamic Linker</a></li><li><a class="toctext" href="../stdlib/profile.html">Profiling</a></li><li><a class="toctext" href="../stdlib/stacktraces.html">StackTraces</a></li><li><a class="toctext" href="../stdlib/simd-types.html">SIMD Support</a></li></ul></li><li><span class="toctext">Developer Documentation</span><ul><li><a class="toctext" href="../devdocs/reflection.html">Reflection and introspection</a></li><li><span class="toctext">Documentation of Julia's Internals</span><ul><li><a class="toctext" href="../devdocs/init.html">Initialization of the Julia runtime</a></li><li><a class="toctext" href="../devdocs/ast.html">Julia ASTs</a></li><li><a class="toctext" href="../devdocs/types.html">More about types</a></li><li><a class="toctext" href="../devdocs/object.html">Memory layout of Julia Objects</a></li><li><a class="toctext" href="../devdocs/eval.html">Eval of Julia code</a></li><li><a class="toctext" href="../devdocs/callconv.html">Calling Conventions</a></li><li><a class="toctext" href="../devdocs/compiler.html">High-level Overview of the Native-Code Generation Process</a></li><li><a class="toctext" href="../devdocs/functions.html">Julia Functions</a></li><li><a class="toctext" href="../devdocs/cartesian.html">Base.Cartesian</a></li><li><a class="toctext" href="../devdocs/meta.html">Talking to the compiler (the <code>:meta</code> mechanism)</a></li><li><a class="toctext" href="../devdocs/subarrays.html">SubArrays</a></li><li><a class="toctext" href="../devdocs/sysimg.html">System Image Building</a></li><li><a class="toctext" href="../devdocs/llvm.html">Working with LLVM</a></li><li><a class="toctext" href="../devdocs/stdio.html">printf() and stdio in the Julia runtime</a></li><li><a class="toctext" href="../devdocs/boundscheck.html">Bounds checking</a></li><li><a class="toctext" href="../devdocs/locks.html">Proper maintenance and care of multi-threading locks</a></li><li><a class="toctext" href="../devdocs/offset-arrays.html">Arrays with custom indices</a></li><li><a class="toctext" href="../devdocs/libgit2.html">Base.LibGit2</a></li><li><a class="toctext" href="../devdocs/require.html">Module loading</a></li></ul></li><li><span class="toctext">Developing/debugging Julia's C code</span><ul><li><a class="toctext" href="../devdocs/backtraces.html">Reporting and analyzing crashes (segfaults)</a></li><li><a class="toctext" href="../devdocs/debuggingtips.html">gdb debugging tips</a></li><li><a class="toctext" href="../devdocs/valgrind.html">Using Valgrind with Julia</a></li><li><a class="toctext" href="../devdocs/sanitizers.html">Sanitizer support</a></li></ul></li></ul></li></ul></nav><article id="docs"><header><nav><ul><li>Manual</li><li><a href="mathematical-operations.html">Mathematical Operations and Elementary Functions</a></li></ul><a class="edit-page" href="https://github.com/JuliaLang/julia/blob/master/doc/src/manual/mathematical-operations.md"><span class="fa"></span> Edit on GitHub</a></nav><hr/><div id="topbar"><span>Mathematical Operations and Elementary Functions</span><a class="fa fa-bars" href="#"></a></div></header><h1><a class="nav-anchor" id="Mathematical-Operations-and-Elementary-Functions-1" href="#Mathematical-Operations-and-Elementary-Functions-1">Mathematical Operations and Elementary Functions</a></h1><p>Julia provides a complete collection of basic arithmetic and bitwise operators across all of its numeric primitive types, as well as providing portable, efficient implementations of a comprehensive collection of standard mathematical functions.</p><h2><a class="nav-anchor" id="Arithmetic-Operators-1" href="#Arithmetic-Operators-1">Arithmetic Operators</a></h2><p>The following <a href="https://en.wikipedia.org/wiki/Arithmetic#Arithmetic_operations">arithmetic operators</a> are supported on all primitive numeric types:</p><table><tr><th>Expression</th><th>Name</th><th>Description</th></tr><tr><td><code>+x</code></td><td>unary plus</td><td>the identity operation</td></tr><tr><td><code>-x</code></td><td>unary minus</td><td>maps values to their additive inverses</td></tr><tr><td><code>x + y</code></td><td>binary plus</td><td>performs addition</td></tr><tr><td><code>x - y</code></td><td>binary minus</td><td>performs subtraction</td></tr><tr><td><code>x * y</code></td><td>times</td><td>performs multiplication</td></tr><tr><td><code>x / y</code></td><td>divide</td><td>performs division</td></tr><tr><td><code>x \ y</code></td><td>inverse divide</td><td>equivalent to <code>y / x</code></td></tr><tr><td><code>x ^ y</code></td><td>power</td><td>raises <code>x</code> to the <code>y</code>th power</td></tr><tr><td><code>x % y</code></td><td>remainder</td><td>equivalent to <code>rem(x,y)</code></td></tr></table><p>as well as the negation on <a href="../stdlib/numbers.html#Core.Bool"><code>Bool</code></a> types:</p><table><tr><th>Expression</th><th>Name</th><th>Description</th></tr><tr><td><code>!x</code></td><td>negation</td><td>changes <code>true</code> to <code>false</code> and vice versa</td></tr></table><p>Julia's promotion system makes arithmetic operations on mixtures of argument types "just work" naturally and automatically. See <a href="conversion-and-promotion.html#conversion-and-promotion-1">Conversion and Promotion</a> for details of the promotion system.</p><p>Here are some simple examples using arithmetic operators:</p><pre><code class="language-julia-repl">julia> 1 + 2 + 3
|
||
6
|
||
|
||
julia> 1 - 2
|
||
-1
|
||
|
||
julia> 3*2/12
|
||
0.5</code></pre><p>(By convention, we tend to space operators more tightly if they get applied before other nearby operators. For instance, we would generally write <code>-x + 2</code> to reflect that first <code>x</code> gets negated, and then <code>2</code> is added to that result.)</p><h2><a class="nav-anchor" id="Bitwise-Operators-1" href="#Bitwise-Operators-1">Bitwise Operators</a></h2><p>The following <a href="https://en.wikipedia.org/wiki/Bitwise_operation#Bitwise_operators">bitwise operators</a> are supported on all primitive integer types:</p><table><tr><th>Expression</th><th>Name</th></tr><tr><td><code>~x</code></td><td>bitwise not</td></tr><tr><td><code>x & y</code></td><td>bitwise and</td></tr><tr><td><code>x | y</code></td><td>bitwise or</td></tr><tr><td><code>x ⊻ y</code></td><td>bitwise xor (exclusive or)</td></tr><tr><td><code>x >>> y</code></td><td><a href="https://en.wikipedia.org/wiki/Logical_shift">logical shift</a> right</td></tr><tr><td><code>x >> y</code></td><td><a href="https://en.wikipedia.org/wiki/Arithmetic_shift">arithmetic shift</a> right</td></tr><tr><td><code>x << y</code></td><td>logical/arithmetic shift left</td></tr></table><p>Here are some examples with bitwise operators:</p><pre><code class="language-julia-repl">julia> ~123
|
||
-124
|
||
|
||
julia> 123 & 234
|
||
106
|
||
|
||
julia> 123 | 234
|
||
251
|
||
|
||
julia> 123 ⊻ 234
|
||
145
|
||
|
||
julia> xor(123, 234)
|
||
145
|
||
|
||
julia> ~UInt32(123)
|
||
0xffffff84
|
||
|
||
julia> ~UInt8(123)
|
||
0x84</code></pre><h2><a class="nav-anchor" id="Updating-operators-1" href="#Updating-operators-1">Updating operators</a></h2><p>Every binary arithmetic and bitwise operator also has an updating version that assigns the result of the operation back into its left operand. The updating version of the binary operator is formed by placing a <code>=</code> immediately after the operator. For example, writing <code>x += 3</code> is equivalent to writing <code>x = x + 3</code>:</p><pre><code class="language-julia-repl">julia> x = 1
|
||
1
|
||
|
||
julia> x += 3
|
||
4
|
||
|
||
julia> x
|
||
4</code></pre><p>The updating versions of all the binary arithmetic and bitwise operators are:</p><pre><code class="language-none">+= -= *= /= \= ÷= %= ^= &= |= ⊻= >>>= >>= <<=</code></pre><div class="admonition note"><div class="admonition-title">Note</div><div class="admonition-text"><p>An updating operator rebinds the variable on the left-hand side. As a result, the type of the variable may change.</p><pre><code class="language-julia-repl">julia> x = 0x01; typeof(x)
|
||
UInt8
|
||
|
||
julia> x *= 2 # Same as x = x * 2
|
||
2
|
||
|
||
julia> typeof(x)
|
||
Int64</code></pre></div></div><h2><a class="nav-anchor" id="man-dot-operators-1" href="#man-dot-operators-1">Vectorized "dot" operators</a></h2><p>For <em>every</em> binary operation like <code>^</code>, there is a corresponding "dot" operation <code>.^</code> that is <em>automatically</em> defined to perform <code>^</code> element-by-element on arrays. For example, <code>[1,2,3] ^ 3</code> is not defined, since there is no standard mathematical meaning to "cubing" an array, but <code>[1,2,3] .^ 3</code> is defined as computing the elementwise (or "vectorized") result <code>[1^3, 2^3, 3^3]</code>. Similarly for unary operators like <code>!</code> or <code>√</code>, there is a corresponding <code>.√</code> that applies the operator elementwise.</p><pre><code class="language-julia-repl">julia> [1,2,3] .^ 3
|
||
3-element Array{Int64,1}:
|
||
1
|
||
8
|
||
27</code></pre><p>More specifically, <code>a .^ b</code> is parsed as the <a href="functions.html#man-vectorized-1">"dot" call</a> <code>(^).(a,b)</code>, which performs a <a href="arrays.html#Broadcasting-1">broadcast</a> operation: it can combine arrays and scalars, arrays of the same size (performing the operation elementwise), and even arrays of different shapes (e.g. combining row and column vectors to produce a matrix). Moreover, like all vectorized "dot calls," these "dot operators" are <em>fusing</em>. For example, if you compute <code>2 .* A.^2 .+ sin.(A)</code> (or equivalently <code>@. 2A^2 + sin(A)</code>, using the <a href="../stdlib/arrays.html#Base.Broadcast.@__dot__"><code>@.</code></a> macro) for an array <code>A</code>, it performs a <em>single</em> loop over <code>A</code>, computing <code>2a^2 + sin(a)</code> for each element of <code>A</code>. In particular, nested dot calls like <code>f.(g.(x))</code> are fused, and "adjacent" binary operators like <code>x .+ 3 .* x.^2</code> are equivalent to nested dot calls <code>(+).(x, (*).(3, (^).(x, 2)))</code>.</p><p>Furthermore, "dotted" updating operators like <code>a .+= b</code> (or <code>@. a += b</code>) are parsed as <code>a .= a .+ b</code>, where <code>.=</code> is a fused <em>in-place</em> assignment operation (see the <a href="functions.html#man-vectorized-1">dot syntax documentation</a>).</p><p>Note the dot syntax is also applicable to user-defined operators. For example, if you define <code>⊗(A,B) = kron(A,B)</code> to give a convenient infix syntax <code>A ⊗ B</code> for Kronecker products (<a href="../stdlib/linalg.html#Base.kron"><code>kron</code></a>), then <code>[A,B] .⊗ [C,D]</code> will compute <code>[A⊗C, B⊗D]</code> with no additional coding.</p><h2><a class="nav-anchor" id="Numeric-Comparisons-1" href="#Numeric-Comparisons-1">Numeric Comparisons</a></h2><p>Standard comparison operations are defined for all the primitive numeric types:</p><table><tr><th>Operator</th><th>Name</th></tr><tr><td><a href="../stdlib/math.html#Base.:=="><code>==</code></a></td><td>equality</td></tr><tr><td><a href="../stdlib/math.html#Base.:!="><code>!=</code></a>, <a href="../stdlib/math.html#Base.:!="><code>≠</code></a></td><td>inequality</td></tr><tr><td><a href="../stdlib/math.html#Base.:<"><code><</code></a></td><td>less than</td></tr><tr><td><a href="../stdlib/math.html#Base.:<="><code><=</code></a>, <a href="../stdlib/math.html#Base.:<="><code>≤</code></a></td><td>less than or equal to</td></tr><tr><td><a href="../stdlib/math.html#Base.:>"><code>></code></a></td><td>greater than</td></tr><tr><td><a href="../stdlib/math.html#Base.:>="><code>>=</code></a>, <a href="../stdlib/math.html#Base.:>="><code>≥</code></a></td><td>greater than or equal to</td></tr></table><p>Here are some simple examples:</p><pre><code class="language-julia-repl">julia> 1 == 1
|
||
true
|
||
|
||
julia> 1 == 2
|
||
false
|
||
|
||
julia> 1 != 2
|
||
true
|
||
|
||
julia> 1 == 1.0
|
||
true
|
||
|
||
julia> 1 < 2
|
||
true
|
||
|
||
julia> 1.0 > 3
|
||
false
|
||
|
||
julia> 1 >= 1.0
|
||
true
|
||
|
||
julia> -1 <= 1
|
||
true
|
||
|
||
julia> -1 <= -1
|
||
true
|
||
|
||
julia> -1 <= -2
|
||
false
|
||
|
||
julia> 3 < -0.5
|
||
false</code></pre><p>Integers are compared in the standard manner – by comparison of bits. Floating-point numbers are compared according to the <a href="https://en.wikipedia.org/wiki/IEEE_754-2008">IEEE 754 standard</a>:</p><ul><li><p>Finite numbers are ordered in the usual manner.</p></li><li><p>Positive zero is equal but not greater than negative zero.</p></li><li><p><code>Inf</code> is equal to itself and greater than everything else except <code>NaN</code>.</p></li><li><p><code>-Inf</code> is equal to itself and less then everything else except <code>NaN</code>.</p></li><li><p><code>NaN</code> is not equal to, not less than, and not greater than anything, including itself.</p></li></ul><p>The last point is potentially surprising and thus worth noting:</p><pre><code class="language-julia-repl">julia> NaN == NaN
|
||
false
|
||
|
||
julia> NaN != NaN
|
||
true
|
||
|
||
julia> NaN < NaN
|
||
false
|
||
|
||
julia> NaN > NaN
|
||
false</code></pre><p>and can cause especial headaches with <a href="arrays.html#Arrays-1">Arrays</a>:</p><pre><code class="language-julia-repl">julia> [1 NaN] == [1 NaN]
|
||
false</code></pre><p>Julia provides additional functions to test numbers for special values, which can be useful in situations like hash key comparisons:</p><table><tr><th>Function</th><th>Tests if</th></tr><tr><td><a href="../stdlib/base.html#Base.isequal-Tuple{Any,Any}"><code>isequal(x, y)</code></a></td><td><code>x</code> and <code>y</code> are identical</td></tr><tr><td><a href="../stdlib/numbers.html#Base.isfinite"><code>isfinite(x)</code></a></td><td><code>x</code> is a finite number</td></tr><tr><td><a href="../stdlib/numbers.html#Base.isinf"><code>isinf(x)</code></a></td><td><code>x</code> is infinite</td></tr><tr><td><a href="../stdlib/numbers.html#Base.isnan"><code>isnan(x)</code></a></td><td><code>x</code> is not a number</td></tr></table><p><a href="../stdlib/base.html#Base.isequal-Tuple{Any,Any}"><code>isequal()</code></a> considers <code>NaN</code>s equal to each other:</p><pre><code class="language-julia-repl">julia> isequal(NaN, NaN)
|
||
true
|
||
|
||
julia> isequal([1 NaN], [1 NaN])
|
||
true
|
||
|
||
julia> isequal(NaN, NaN32)
|
||
true</code></pre><p><code>isequal()</code> can also be used to distinguish signed zeros:</p><pre><code class="language-julia-repl">julia> -0.0 == 0.0
|
||
true
|
||
|
||
julia> isequal(-0.0, 0.0)
|
||
false</code></pre><p>Mixed-type comparisons between signed integers, unsigned integers, and floats can be tricky. A great deal of care has been taken to ensure that Julia does them correctly.</p><p>For other types, <code>isequal()</code> defaults to calling <a href="../stdlib/math.html#Base.:=="><code>==()</code></a>, so if you want to define equality for your own types then you only need to add a <a href="../stdlib/math.html#Base.:=="><code>==()</code></a> method. If you define your own equality function, you should probably define a corresponding <a href="../stdlib/base.html#Base.hash"><code>hash()</code></a> method to ensure that <code>isequal(x,y)</code> implies <code>hash(x) == hash(y)</code>.</p><h3><a class="nav-anchor" id="Chaining-comparisons-1" href="#Chaining-comparisons-1">Chaining comparisons</a></h3><p>Unlike most languages, with the <a href="https://en.wikipedia.org/wiki/Python_syntax_and_semantics#Comparison_operators">notable exception of Python</a>, comparisons can be arbitrarily chained:</p><pre><code class="language-julia-repl">julia> 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5
|
||
true</code></pre><p>Chaining comparisons is often quite convenient in numerical code. Chained comparisons use the <code>&&</code> operator for scalar comparisons, and the <a href="../stdlib/math.html#Base.:&"><code>&</code></a> operator for elementwise comparisons, which allows them to work on arrays. For example, <code>0 .< A .< 1</code> gives a boolean array whose entries are true where the corresponding elements of <code>A</code> are between 0 and 1.</p><p>Note the evaluation behavior of chained comparisons:</p><pre><code class="language-julia-repl">julia> v(x) = (println(x); x)
|
||
v (generic function with 1 method)
|
||
|
||
julia> v(1) < v(2) <= v(3)
|
||
2
|
||
1
|
||
3
|
||
true
|
||
|
||
julia> v(1) > v(2) <= v(3)
|
||
2
|
||
1
|
||
false</code></pre><p>The middle expression is only evaluated once, rather than twice as it would be if the expression were written as <code>v(1) < v(2) && v(2) <= v(3)</code>. However, the order of evaluations in a chained comparison is undefined. It is strongly recommended not to use expressions with side effects (such as printing) in chained comparisons. If side effects are required, the short-circuit <code>&&</code> operator should be used explicitly (see <a href="control-flow.html#Short-Circuit-Evaluation-1">Short-Circuit Evaluation</a>).</p><h3><a class="nav-anchor" id="Elementary-Functions-1" href="#Elementary-Functions-1">Elementary Functions</a></h3><p>Julia provides a comprehensive collection of mathematical functions and operators. These mathematical operations are defined over as broad a class of numerical values as permit sensible definitions, including integers, floating-point numbers, rationals, and complex numbers, wherever such definitions make sense.</p><p>Moreover, these functions (like any Julia function) can be applied in "vectorized" fashion to arrays and other collections with the <a href="functions.html#man-vectorized-1">dot syntax</a> <code>f.(A)</code>, e.g. <code>sin.(A)</code> will compute the sine of each element of an array <code>A</code>.</p><h2><a class="nav-anchor" id="Operator-Precedence-1" href="#Operator-Precedence-1">Operator Precedence</a></h2><p>Julia applies the following order of operations, from highest precedence to lowest:</p><table><tr><th>Category</th><th>Operators</th></tr><tr><td>Syntax</td><td><code>.</code> followed by <code>::</code></td></tr><tr><td>Exponentiation</td><td><code>^</code></td></tr><tr><td>Fractions</td><td><code>//</code></td></tr><tr><td>Multiplication</td><td><code>* / % & \</code></td></tr><tr><td>Bitshifts</td><td><code><< >> >>></code></td></tr><tr><td>Addition</td><td><code>+ - | ⊻</code></td></tr><tr><td>Syntax</td><td><code>: ..</code> followed by <code>|></code></td></tr><tr><td>Comparisons</td><td><code>> < >= <= == === != !== <:</code></td></tr><tr><td>Control flow</td><td><code>&&</code> followed by <code>||</code> followed by <code>?</code></td></tr><tr><td>Assignments</td><td><code>= += -= *= /= //= \= ^= ÷= %= |= &= ⊻= <<= >>= >>>=</code></td></tr></table><p>For a complete list of <em>every</em> Julia operator's precedence, see the top of this file: <a href="https://github.com/JuliaLang/julia/blob/master/src/julia-parser.scm"><code>src/julia-parser.scm</code></a></p><p>You can also find the numerical precedence for any given operator via the built-in function <code>Base.operator_precedence</code>, where higher numbers take precedence:</p><pre><code class="language-julia-repl">julia> Base.operator_precedence(:+), Base.operator_precedence(:*), Base.operator_precedence(:.)
|
||
(9, 11, 15)
|
||
|
||
julia> Base.operator_precedence(:+=), Base.operator_precedence(:(=)) # (Note the necessary parens on `:(=)`)
|
||
(1, 1)</code></pre><h2><a class="nav-anchor" id="Numerical-Conversions-1" href="#Numerical-Conversions-1">Numerical Conversions</a></h2><p>Julia supports three forms of numerical conversion, which differ in their handling of inexact conversions.</p><ul><li><p>The notation <code>T(x)</code> or <code>convert(T,x)</code> converts <code>x</code> to a value of type <code>T</code>.</p><ul><li><p>If <code>T</code> is a floating-point type, the result is the nearest representable value, which could be positive or negative infinity.</p></li><li><p>If <code>T</code> is an integer type, an <code>InexactError</code> is raised if <code>x</code> is not representable by <code>T</code>.</p></li></ul></li><li><p><code>x % T</code> converts an integer <code>x</code> to a value of integer type <code>T</code> congruent to <code>x</code> modulo <code>2^n</code>, where <code>n</code> is the number of bits in <code>T</code>. In other words, the binary representation is truncated to fit.</p></li><li><p>The <a href="mathematical-operations.html#Rounding-functions-1">Rounding functions</a> take a type <code>T</code> as an optional argument. For example, <code>round(Int,x)</code> is a shorthand for <code>Int(round(x))</code>.</p></li></ul><p>The following examples show the different forms.</p><pre><code class="language-julia-repl">julia> Int8(127)
|
||
127
|
||
|
||
julia> Int8(128)
|
||
ERROR: InexactError()
|
||
Stacktrace:
|
||
[1] Int8(::Int64) at ./sysimg.jl:77
|
||
|
||
julia> Int8(127.0)
|
||
127
|
||
|
||
julia> Int8(3.14)
|
||
ERROR: InexactError()
|
||
Stacktrace:
|
||
[1] convert(::Type{Int8}, ::Float64) at ./float.jl:658
|
||
[2] Int8(::Float64) at ./sysimg.jl:77
|
||
|
||
julia> Int8(128.0)
|
||
ERROR: InexactError()
|
||
Stacktrace:
|
||
[1] convert(::Type{Int8}, ::Float64) at ./float.jl:658
|
||
[2] Int8(::Float64) at ./sysimg.jl:77
|
||
|
||
julia> 127 % Int8
|
||
127
|
||
|
||
julia> 128 % Int8
|
||
-128
|
||
|
||
julia> round(Int8,127.4)
|
||
127
|
||
|
||
julia> round(Int8,127.6)
|
||
ERROR: InexactError()
|
||
Stacktrace:
|
||
[1] trunc(::Type{Int8}, ::Float64) at ./float.jl:651
|
||
[2] round(::Type{Int8}, ::Float64) at ./float.jl:337</code></pre><p>See <a href="conversion-and-promotion.html#conversion-and-promotion-1">Conversion and Promotion</a> for how to define your own conversions and promotions.</p><h3><a class="nav-anchor" id="Rounding-functions-1" href="#Rounding-functions-1">Rounding functions</a></h3><table><tr><th>Function</th><th>Description</th><th>Return type</th></tr><tr><td><a href="../stdlib/dates.html#Base.round-Tuple{Base.Dates.TimeType,Base.Dates.Period,RoundingMode{:NearestTiesUp}}"><code>round(x)</code></a></td><td>round <code>x</code> to the nearest integer</td><td><code>typeof(x)</code></td></tr><tr><td><a href="../stdlib/dates.html#Base.round-Tuple{Base.Dates.TimeType,Base.Dates.Period,RoundingMode{:NearestTiesUp}}"><code>round(T, x)</code></a></td><td>round <code>x</code> to the nearest integer</td><td><code>T</code></td></tr><tr><td><a href="../stdlib/dates.html#Base.floor-Tuple{Base.Dates.TimeType,Base.Dates.Period}"><code>floor(x)</code></a></td><td>round <code>x</code> towards <code>-Inf</code></td><td><code>typeof(x)</code></td></tr><tr><td><a href="../stdlib/dates.html#Base.floor-Tuple{Base.Dates.TimeType,Base.Dates.Period}"><code>floor(T, x)</code></a></td><td>round <code>x</code> towards <code>-Inf</code></td><td><code>T</code></td></tr><tr><td><a href="../stdlib/dates.html#Base.ceil-Tuple{Base.Dates.TimeType,Base.Dates.Period}"><code>ceil(x)</code></a></td><td>round <code>x</code> towards <code>+Inf</code></td><td><code>typeof(x)</code></td></tr><tr><td><a href="../stdlib/dates.html#Base.ceil-Tuple{Base.Dates.TimeType,Base.Dates.Period}"><code>ceil(T, x)</code></a></td><td>round <code>x</code> towards <code>+Inf</code></td><td><code>T</code></td></tr><tr><td><a href="../stdlib/dates.html#Base.trunc-Tuple{Base.Dates.TimeType,Type{Base.Dates.Period}}"><code>trunc(x)</code></a></td><td>round <code>x</code> towards zero</td><td><code>typeof(x)</code></td></tr><tr><td><a href="../stdlib/dates.html#Base.trunc-Tuple{Base.Dates.TimeType,Type{Base.Dates.Period}}"><code>trunc(T, x)</code></a></td><td>round <code>x</code> towards zero</td><td><code>T</code></td></tr></table><h3><a class="nav-anchor" id="Division-functions-1" href="#Division-functions-1">Division functions</a></h3><table><tr><th>Function</th><th>Description</th></tr><tr><td><a href="../stdlib/math.html#Base.div"><code>div(x,y)</code></a></td><td>truncated division; quotient rounded towards zero</td></tr><tr><td><a href="../stdlib/math.html#Base.fld"><code>fld(x,y)</code></a></td><td>floored division; quotient rounded towards <code>-Inf</code></td></tr><tr><td><a href="../stdlib/math.html#Base.cld"><code>cld(x,y)</code></a></td><td>ceiling division; quotient rounded towards <code>+Inf</code></td></tr><tr><td><a href="../stdlib/math.html#Base.rem"><code>rem(x,y)</code></a></td><td>remainder; satisfies <code>x == div(x,y)*y + rem(x,y)</code>; sign matches <code>x</code></td></tr><tr><td><a href="../stdlib/math.html#Base.mod"><code>mod(x,y)</code></a></td><td>modulus; satisfies <code>x == fld(x,y)*y + mod(x,y)</code>; sign matches <code>y</code></td></tr><tr><td><a href="../stdlib/math.html#Base.mod1"><code>mod1(x,y)</code></a></td><td><code>mod()</code> with offset 1; returns <code>r∈(0,y]</code> for <code>y>0</code> or <code>r∈[y,0)</code> for <code>y<0</code>, where <code>mod(r, y) == mod(x, y)</code></td></tr><tr><td><a href="../stdlib/math.html#Base.Math.mod2pi"><code>mod2pi(x)</code></a></td><td>modulus with respect to 2pi; <code>0 <= mod2pi(x) < 2pi</code></td></tr><tr><td><a href="../stdlib/math.html#Base.divrem"><code>divrem(x,y)</code></a></td><td>returns <code>(div(x,y),rem(x,y))</code></td></tr><tr><td><a href="../stdlib/math.html#Base.fldmod"><code>fldmod(x,y)</code></a></td><td>returns <code>(fld(x,y),mod(x,y))</code></td></tr><tr><td><a href="../stdlib/math.html#Base.gcd"><code>gcd(x,y...)</code></a></td><td>greatest positive common divisor of <code>x</code>, <code>y</code>,...</td></tr><tr><td><a href="../stdlib/math.html#Base.lcm"><code>lcm(x,y...)</code></a></td><td>least positive common multiple of <code>x</code>, <code>y</code>,...</td></tr></table><h3><a class="nav-anchor" id="Sign-and-absolute-value-functions-1" href="#Sign-and-absolute-value-functions-1">Sign and absolute value functions</a></h3><table><tr><th>Function</th><th>Description</th></tr><tr><td><a href="../stdlib/math.html#Base.abs"><code>abs(x)</code></a></td><td>a positive value with the magnitude of <code>x</code></td></tr><tr><td><a href="../stdlib/math.html#Base.abs2"><code>abs2(x)</code></a></td><td>the squared magnitude of <code>x</code></td></tr><tr><td><a href="../stdlib/math.html#Base.sign"><code>sign(x)</code></a></td><td>indicates the sign of <code>x</code>, returning -1, 0, or +1</td></tr><tr><td><a href="../stdlib/math.html#Base.signbit"><code>signbit(x)</code></a></td><td>indicates whether the sign bit is on (true) or off (false)</td></tr><tr><td><a href="../stdlib/math.html#Base.copysign"><code>copysign(x,y)</code></a></td><td>a value with the magnitude of <code>x</code> and the sign of <code>y</code></td></tr><tr><td><a href="../stdlib/math.html#Base.flipsign"><code>flipsign(x,y)</code></a></td><td>a value with the magnitude of <code>x</code> and the sign of <code>x*y</code></td></tr></table><h3><a class="nav-anchor" id="Powers,-logs-and-roots-1" href="#Powers,-logs-and-roots-1">Powers, logs and roots</a></h3><table><tr><th>Function</th><th>Description</th></tr><tr><td><a href="../stdlib/math.html#Base.sqrt"><code>sqrt(x)</code></a>, <code>√x</code></td><td>square root of <code>x</code></td></tr><tr><td><a href="../stdlib/math.html#Base.Math.cbrt"><code>cbrt(x)</code></a>, <code>∛x</code></td><td>cube root of <code>x</code></td></tr><tr><td><a href="../stdlib/math.html#Base.Math.hypot"><code>hypot(x,y)</code></a></td><td>hypotenuse of right-angled triangle with other sides of length <code>x</code> and <code>y</code></td></tr><tr><td><a href="../stdlib/math.html#Base.exp"><code>exp(x)</code></a></td><td>natural exponential function at <code>x</code></td></tr><tr><td><a href="../stdlib/math.html#Base.expm1"><code>expm1(x)</code></a></td><td>accurate <code>exp(x)-1</code> for <code>x</code> near zero</td></tr><tr><td><a href="../stdlib/math.html#Base.Math.ldexp"><code>ldexp(x,n)</code></a></td><td><code>x*2^n</code> computed efficiently for integer values of <code>n</code></td></tr><tr><td><a href="../stdlib/math.html#Base.log-Tuple{Any}"><code>log(x)</code></a></td><td>natural logarithm of <code>x</code></td></tr><tr><td><a href="../stdlib/math.html#Base.log-Tuple{Any}"><code>log(b,x)</code></a></td><td>base <code>b</code> logarithm of <code>x</code></td></tr><tr><td><a href="../stdlib/math.html#Base.log2"><code>log2(x)</code></a></td><td>base 2 logarithm of <code>x</code></td></tr><tr><td><a href="../stdlib/math.html#Base.log10"><code>log10(x)</code></a></td><td>base 10 logarithm of <code>x</code></td></tr><tr><td><a href="../stdlib/math.html#Base.log1p"><code>log1p(x)</code></a></td><td>accurate <code>log(1+x)</code> for <code>x</code> near zero</td></tr><tr><td><a href="../stdlib/numbers.html#Base.Math.exponent"><code>exponent(x)</code></a></td><td>binary exponent of <code>x</code></td></tr><tr><td><a href="../stdlib/numbers.html#Base.Math.significand"><code>significand(x)</code></a></td><td>binary significand (a.k.a. mantissa) of a floating-point number <code>x</code></td></tr></table><p>For an overview of why functions like <a href="../stdlib/math.html#Base.Math.hypot"><code>hypot()</code></a>, <a href="../stdlib/math.html#Base.expm1"><code>expm1()</code></a>, and <a href="../stdlib/math.html#Base.log1p"><code>log1p()</code></a> are necessary and useful, see John D. Cook's excellent pair of blog posts on the subject: <a href="https://www.johndcook.com/blog/2010/06/07/math-library-functions-that-seem-unnecessary/">expm1, log1p, erfc</a>, and <a href="https://www.johndcook.com/blog/2010/06/02/whats-so-hard-about-finding-a-hypotenuse/">hypot</a>.</p><h3><a class="nav-anchor" id="Trigonometric-and-hyperbolic-functions-1" href="#Trigonometric-and-hyperbolic-functions-1">Trigonometric and hyperbolic functions</a></h3><p>All the standard trigonometric and hyperbolic functions are also defined:</p><pre><code class="language-none">sin cos tan cot sec csc
|
||
sinh cosh tanh coth sech csch
|
||
asin acos atan acot asec acsc
|
||
asinh acosh atanh acoth asech acsch
|
||
sinc cosc atan2</code></pre><p>These are all single-argument functions, with the exception of <a href="https://en.wikipedia.org/wiki/Atan2">atan2</a>, which gives the angle in <a href="https://en.wikipedia.org/wiki/Radian">radians</a> between the <em>x</em>-axis and the point specified by its arguments, interpreted as <em>x</em> and <em>y</em> coordinates.</p><p>Additionally, <a href="../stdlib/math.html#Base.Math.sinpi"><code>sinpi(x)</code></a> and <a href="../stdlib/math.html#Base.Math.cospi"><code>cospi(x)</code></a> are provided for more accurate computations of <a href="../stdlib/math.html#Base.sin"><code>sin(pi*x)</code></a> and <a href="../stdlib/math.html#Base.cos"><code>cos(pi*x)</code></a> respectively.</p><p>In order to compute trigonometric functions with degrees instead of radians, suffix the function with <code>d</code>. For example, <a href="../stdlib/math.html#Base.Math.sind"><code>sind(x)</code></a> computes the sine of <code>x</code> where <code>x</code> is specified in degrees. The complete list of trigonometric functions with degree variants is:</p><pre><code class="language-none">sind cosd tand cotd secd cscd
|
||
asind acosd atand acotd asecd acscd</code></pre><h3><a class="nav-anchor" id="Special-functions-1" href="#Special-functions-1">Special functions</a></h3><table><tr><th>Function</th><th>Description</th></tr><tr><td><a href="../stdlib/math.html#Base.Math.gamma"><code>gamma(x)</code></a></td><td><a href="https://en.wikipedia.org/wiki/Gamma_function">gamma function</a> at <code>x</code></td></tr><tr><td><a href="../stdlib/math.html#Base.Math.lgamma"><code>lgamma(x)</code></a></td><td>accurate <code>log(gamma(x))</code> for large <code>x</code></td></tr><tr><td><a href="../stdlib/math.html#Base.Math.lfact"><code>lfact(x)</code></a></td><td>accurate <code>log(factorial(x))</code> for large <code>x</code>; same as <code>lgamma(x+1)</code> for <code>x > 1</code>, zero otherwise</td></tr><tr><td><a href="../stdlib/math.html#Base.Math.beta"><code>beta(x,y)</code></a></td><td><a href="https://en.wikipedia.org/wiki/Beta_function">beta function</a> at <code>x,y</code></td></tr><tr><td><a href="../stdlib/math.html#Base.Math.lbeta"><code>lbeta(x,y)</code></a></td><td>accurate <code>log(beta(x,y))</code> for large <code>x</code> or <code>y</code></td></tr></table><footer><hr/><a class="previous" href="integers-and-floating-point-numbers.html"><span class="direction">Previous</span><span class="title">Integers and Floating-Point Numbers</span></a><a class="next" href="complex-and-rational-numbers.html"><span class="direction">Next</span><span class="title">Complex and Rational Numbers</span></a></footer></article></body></html>
|