Movatterモバイル変換


[0]ホーム

URL:


GitHub

Mathematical Operations and Elementary Functions

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.

Arithmetic Operators

The followingarithmetic operators are supported on all primitive numeric types:

ExpressionNameDescription
+xunary plusthe identity operation
-xunary minusmaps values to their additive inverses
x + ybinary plusperforms addition
x - ybinary minusperforms subtraction
x * ytimesperforms multiplication
x / ydivideperforms division
x ÷ yinteger dividex / y, truncated to an integer
x \ yinverse divideequivalent toy / x
x ^ ypowerraisesx to theyth power
x % yremainderequivalent torem(x, y)

A numeric literal placed directly before an identifier or parentheses, e.g.2x or2(x + y), is treated as a multiplication, except with higher precedence than other binary operations. SeeNumeric Literal Coefficients for details.

Julia's promotion system makes arithmetic operations on mixtures of argument types "just work" naturally and automatically. SeeConversion and Promotion for details of the promotion system.

The ÷ sign can be conveniently typed by writing\div<tab> to the REPL or Julia IDE. See themanual section on Unicode input for more information.

Here are some simple examples using arithmetic operators:

julia> 1 + 2 + 36julia> 1 - 2-1julia> 3*2/120.5

(By convention, we tend to space operators more tightly if they get applied before other nearby operators. For instance, we would generally write-x + 2 to reflect that firstx gets negated, and then2 is added to that result.)

When used in multiplication,false acts as astrong zero:

julia> NaN * false0.0julia> false * Inf0.0

This is useful for preventing the propagation ofNaN values in quantities that are known to be zero. SeeKnuth (1992) for motivation.

Boolean Operators

The followingBoolean operators are supported onBool types:

ExpressionName
!xnegation
x && yshort-circuiting and
x || yshort-circuiting or

Negation changestrue tofalse and vice versa. The short-circuiting operations are explained on the linked page.

Note thatBool is an integer type and all the usual promotion rules and numeric operators are also defined on it.

Bitwise Operators

The followingbitwise operators are supported on all primitive integer types:

ExpressionName
~xbitwise not
x & ybitwise and
x | ybitwise or
x ⊻ ybitwise xor (exclusive or)
x ⊼ ybitwise nand (not and)
x ⊽ ybitwise nor (not or)
x >>> ylogical shift right
x >> yarithmetic shift right
x << ylogical/arithmetic shift left

Here are some examples with bitwise operators:

julia> ~123-124julia> 123 & 234106julia> 123 | 234251julia> 123 ⊻ 234145julia> xor(123, 234)145julia> nand(123, 123)-124julia> 123 ⊼ 123-124julia> nor(123, 124)-128julia> 123 ⊽ 124-128julia> ~UInt32(123)0xffffff84julia> ~UInt8(123)0x84

Updating operators

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= immediately after the operator. For example, writingx += 3 is equivalent to writingx = x + 3:

julia> x = 11julia> x += 34julia> x4

The updating versions of all the binary arithmetic and bitwise operators are:

+=  -=  *=  /=  \=  ÷=  %=  ^=  &=  |=  ⊻=  >>>=  >>=  <<=
Note

An updating operator rebinds the variable on the left-hand side. As a result, the type of the variable may change.

julia> x = 0x01; typeof(x)UInt8julia> x *= 2 # Same as x = x * 22julia> typeof(x)Int64

Vectorized "dot" operators

Forevery binary operation like^, there is a corresponding "dot" operation.^ that isautomatically defined to perform^ element-by-element on arrays. For example,[1, 2, 3] ^ 3 is not defined, since there is no standard mathematical meaning to "cubing" a (non-square) array, but[1, 2, 3] .^ 3 is defined as computing the elementwise (or "vectorized") result[1^3, 2^3, 3^3]. Similarly for unary operators like! or, there is a corresponding.√ that applies the operator elementwise.

julia> [1, 2, 3] .^ 33-element Vector{Int64}:  1  8 27

More specifically,a .^ b is parsed as the"dot" call(^).(a,b), which performs abroadcast 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" arefusing. For example, if you compute2 .* A.^2 .+ sin.(A) (or equivalently@. 2A^2 + sin(A), using the@. macro) for an arrayA, it performs asingle loop overA, computing2a^2 + sin(a) for each elementa ofA. In particular, nested dot calls likef.(g.(x)) are fused, and "adjacent" binary operators likex .+ 3 .* x.^2 are equivalent to nested dot calls(+).(x, (*).(3, (^).(x, 2))).

Furthermore, "dotted" updating operators likea .+= b (or@. a += b) are parsed asa .= a .+ b, where.= is a fusedin-place assignment operation (see thedot syntax documentation).

Note the dot syntax is also applicable to user-defined operators. For example, if you define⊗(A, B) = kron(A, B) to give a convenient infix syntaxA ⊗ B for Kronecker products (kron), then[A, B] .⊗ [C, D] will compute[A⊗C, B⊗D] with no additional coding.

Combining dot operators with numeric literals can be ambiguous. For example, it is not clear whether1.+x means1. + x or1 .+ x. Therefore this syntax is disallowed, and spaces must be used around the operator in such cases.

Numeric Comparisons

Standard comparison operations are defined for all the primitive numeric types:

OperatorName
==equality
!=,inequality
<less than
<=,less than or equal to
>greater than
>=,greater than or equal to

Here are some simple examples:

julia> 1 == 1truejulia> 1 == 2falsejulia> 1 != 2truejulia> 1 == 1.0truejulia> 1 < 2truejulia> 1.0 > 3falsejulia> 1 >= 1.0truejulia> -1 <= 1truejulia> -1 <= -1truejulia> -1 <= -2falsejulia> 3 < -0.5false

Integers are compared in the standard manner – by comparison of bits. Floating-point numbers are compared according to theIEEE 754 standard:

The last point is potentially surprising and thus worth noting:

julia> NaN == NaNfalsejulia> NaN != NaNtruejulia> NaN < NaNfalsejulia> NaN > NaNfalse

and can cause headaches when working witharrays:

julia> [1 NaN] == [1 NaN]false

Julia provides additional functions to test numbers for special values, which can be useful in situations like hash key comparisons:

FunctionTests if
isequal(x, y)x andy are identical
isfinite(x)x is a finite number
isinf(x)x is infinite
isnan(x)x is not a number

isequal considersNaNs equal to each other:

julia> isequal(NaN, NaN)truejulia> isequal([1 NaN], [1 NaN])truejulia> isequal(NaN, NaN32)true

isequal can also be used to distinguish signed zeros:

julia> -0.0 == 0.0truejulia> isequal(-0.0, 0.0)false

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.

For other types,isequal defaults to calling==, so if you want to define equality for your own types then you only need to add a== method. If you define your own equality function, you should probably define a correspondinghash method to ensure thatisequal(x,y) implieshash(x) == hash(y).

Chaining comparisons

Unlike most languages, with thenotable exception of Python, comparisons can be arbitrarily chained:

julia> 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5true

Chaining comparisons is often quite convenient in numerical code. Chained comparisons use the&& operator for scalar comparisons, and the& operator for elementwise comparisons, which allows them to work on arrays. For example,0 .< A .< 1 gives a boolean array whose entries are true where the corresponding elements ofA are between 0 and 1.

Note the evaluation behavior of chained comparisons:

julia> v(x) = (println(x); x)v (generic function with 1 method)julia> v(1) < v(2) <= v(3)213truejulia> v(1) > v(2) <= v(3)21false

The middle expression is only evaluated once, rather than twice as it would be if the expression were written asv(1) < v(2) && v(2) <= v(3). 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&& operator should be used explicitly (seeShort-Circuit Evaluation).

Elementary Functions

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.

Moreover, these functions (like any Julia function) can be applied in "vectorized" fashion to arrays and other collections with thedot syntaxf.(A), e.g.sin.(A) will compute the sine of each element of an arrayA.

Operator Precedence and Associativity

Julia applies the following order and associativity of operations, from highest precedence to lowest:

CategoryOperatorsAssociativity
Syntax. followed by::Left
Exponentiation^Right
Unary+ - ! ~ ¬ √ ∛ ∜ ⋆ ± ∓ <: >:Right[1]
Bitshifts<< >> >>>Left
Fractions//Left
Multiplication* / % & \ ÷Left[2]
Addition+ - | ⊻Left[2]
Syntax: ..Left
Syntax|>Left
Syntax<|Right
Comparisons> < >= <= == === != !== <:Non-associative
Control flow&& followed by|| followed by?Right
Pair=>Right
Assignments= += -= *= /= //= \= ^= ÷= %= |= &= ⊻= <<= >>= >>>=Right

For a complete list ofevery Julia operator's precedence, see the top of this file:src/julia-parser.scm. Note that some of the operators there are not defined in theBase module but may be given definitions by standard libraries, packages or user code.

You can also find the numerical precedence for any given operator via the built-in functionBase.operator_precedence, where higher numbers take precedence:

julia> Base.operator_precedence(:+), Base.operator_precedence(:*), Base.operator_precedence(:.)(11, 12, 17)julia> Base.operator_precedence(:sin), Base.operator_precedence(:+=), Base.operator_precedence(:(=))  # (Note the necessary parens on `:(=)`)(0, 1, 1)

A symbol representing the operator associativity can also be found by calling the built-in functionBase.operator_associativity:

julia> Base.operator_associativity(:-), Base.operator_associativity(:+), Base.operator_associativity(:^)(:left, :none, :right)julia> Base.operator_associativity(:⊗), Base.operator_associativity(:sin), Base.operator_associativity(:→)(:left, :none, :right)

Note that symbols such as:sin return precedence0. This value represents invalid operators and not operators of lowest precedence. Similarly, such operators are assigned associativity:none.

Numeric literal coefficients, e.g.2x, are treated as multiplications with higher precedence than any other binary operation, with the exception of^ where they have higher precedence only as the exponent.

julia> x = 3; 2x^218julia> x = 3; 2^2x64

Juxtaposition parses like a unary operator, which has the same natural asymmetry around exponents:-x^y and2x^y parse as-(x^y) and2(x^y) whereasx^-y andx^2y parse asx^(-y) andx^(2y).

Numerical Conversions

Julia supports three forms of numerical conversion, which differ in their handling of inexact conversions.

The following examples show the different forms.

julia> Int8(127)127julia> Int8(128)ERROR: InexactError: trunc(Int8, 128)Stacktrace:[...]julia> Int8(127.0)127julia> Int8(3.14)ERROR: InexactError: Int8(3.14)Stacktrace:[...]julia> Int8(128.0)ERROR: InexactError: Int8(128.0)Stacktrace:[...]julia> 127 % Int8127julia> 128 % Int8-128julia> round(Int8,127.4)127julia> round(Int8,127.6)ERROR: InexactError: Int8(128.0)Stacktrace:[...]

SeeConversion and Promotion for how to define your own conversions and promotions.

Rounding functions

FunctionDescriptionReturn type
round(x)roundx to the nearest integertypeof(x)
round(T, x)roundx to the nearest integerT
floor(x)roundx towards-Inftypeof(x)
floor(T, x)roundx towards-InfT
ceil(x)roundx towards+Inftypeof(x)
ceil(T, x)roundx towards+InfT
trunc(x)roundx towards zerotypeof(x)
trunc(T, x)roundx towards zeroT

Division functions

FunctionDescription
div(x, y),x÷ytruncated division; quotient rounded towards zero
fld(x, y)floored division; quotient rounded towards-Inf
cld(x, y)ceiling division; quotient rounded towards+Inf
rem(x, y),x%yremainder; satisfiesx == div(x, y)*y + rem(x, y); sign matchesx
mod(x, y)modulus; satisfiesx == fld(x, y)*y + mod(x, y); sign matchesy
mod1(x, y)mod with offset 1; returnsr∈(0, y] fory>0 orr∈[y, 0) fory<0, wheremod(r, y) == mod(x, y)
mod2pi(x)modulus with respect to 2pi;0 <= mod2pi(x) < 2pi
divrem(x, y)returns(div(x, y),rem(x, y))
fldmod(x, y)returns(fld(x, y), mod(x, y))
gcd(x, y...)greatest positive common divisor ofx,y,...
lcm(x, y...)least positive common multiple ofx,y,...

Sign and absolute value functions

FunctionDescription
abs(x)a positive value with the magnitude ofx
abs2(x)the squared magnitude ofx
sign(x)indicates the sign ofx, returning -1, 0, or +1
signbit(x)indicates whether the sign bit is on (true) or off (false)
copysign(x, y)a value with the magnitude ofx and the sign ofy
flipsign(x, y)a value with the magnitude ofx and the sign ofx*y

Powers, logs and roots

FunctionDescription
sqrt(x),√xsquare root ofx
cbrt(x),∛xcube root ofx
hypot(x, y)hypotenuse of right-angled triangle with other sides of lengthx andy
exp(x)natural exponential function atx
expm1(x)accurateexp(x) - 1 forx near zero
ldexp(x, n)x * 2^n computed efficiently for integer values ofn
log(x)natural logarithm ofx
log(b, x)baseb logarithm ofx
log2(x)base 2 logarithm ofx
log10(x)base 10 logarithm ofx
log1p(x)accuratelog(1 + x) forx near zero
exponent(x)binary exponent ofx
significand(x)binary significand (a.k.a. mantissa) of a floating-point numberx

For an overview of why functions likehypot,expm1, andlog1p are necessary and useful, see John D. Cook's excellent pair of blog posts on the subject:expm1, log1p, erfc, andhypot.

Trigonometric and hyperbolic functions

All the standard trigonometric and hyperbolic functions are also defined:

sin    cos    tan    cot    sec    cscsinh   cosh   tanh   coth   sech   cschasin   acos   atan   acot   asec   acscasinh  acosh  atanh  acoth  asech  acschsinc   cosc

These are all single-argument functions, withatan also accepting two arguments corresponding to a traditionalatan2 function.

Additionally,sinpi(x) andcospi(x) are provided for more accurate computations ofsin(pi * x) andcos(pi * x) respectively.

In order to compute trigonometric functions with degrees instead of radians, suffix the function withd. For example,sind(x) computes the sine ofx wherex is specified in degrees. The complete list of trigonometric functions with degree variants is:

sind   cosd   tand   cotd   secd   cscdasind  acosd  atand  acotd  asecd  acscd

Special functions

Many other special mathematical functions are provided by the packageSpecialFunctions.jl.

  • 1The 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)).
  • 2The operators+,++ and* are non-associative.a + b + c is parsed as+(a, b, c) not+(+(a, b), c). However, the fallback methods for+(a, b, c, d...) and*(a, b, c, d...) both default to left-associative evaluation.

Settings


This document was generated withDocumenter.jl version 1.8.0 onWednesday 9 July 2025. Using Julia version 1.11.6.


[8]ページ先頭

©2009-2025 Movatter.jp