/
always returns a fractional number; if you need an integer part from dividing two integers, you need to use the operation div(m, n)
or the infix equivalent m ÷ n
.Int
) - 2
, 3
, -42
UInt
( UInt
) - 0x12345
Float32
, Float64
) - 1.0
, 3.1415
, -Inf
, NaN
Rational
) - 3//3
, 7//2
Real
) - All of the aboveComplex
) - 3+4*im
, 2//3+2//3*im
, 3.0+0.0*im
( im
is an imaginary unit, only a number with an explicitly written imaginary part is considered complex)Number
) - all of the above'a'
- character ( Char
)"a"
- string ( String
)x = [1, 2, 3]
- set the array by direct enumeration of elementszeros(length)
for an array of zeros, ones(length)
for an array of ones, rand(length)
for an array of random numbers, etc.(2, 5.3, "k")
- regular tuple(a = 3, b = 4)
- the named tuple julia> x = (a = 5, b = 12) (a = 5, b = 12) julia> x[1] 5 julia> sqrt(xa^2 + x[2]^2) 13.0
julia> x = Dict('a' => 5, 'b' => 12) Dict{Char,Int64} with 2 entries: 'a' => 5 'b' => 12 julia> x['c'] = 13 13 julia> x Dict{Char,Int64} with 3 entries: 'a' => 5 'c' => 13 'b' => 12
julia> x = 7; x + 2 9 julia> x = 42.0; x * 4 168.0
if <condition>
and ends with the word end
. You can also have an else
flower or else
if a flower: if x > y println("X is more than Y") elseif x == y println("X and Y are equal") else println("X is less than Y") end
while
and for
. The second works as in Python, i.e. iterates over the collection. Frequent use is iteration over a range of values, the syntax of which is start[:increment]:end
. Unlike Python, the range includes both initial and final values, i.e. the empty range will not be 1:1
(this is a range of one value 1), but 1:0
. The end of the loop body is marked with the word end
. julia> for i in 1:3; print(i, " "); end # 1 3 1 ( ) 1 2 3 julia> for i in 1:2:3; print(i, " "); end # 1 3 2 1 3
function
keyword, the function
definition is also completed by the word end
. Arguments with default values and named arguments are supported. function square(x) return x * x end function cube(x) x * square(x) # ; return end function root(x, degree = 2) # degree return x^(1.0/degree) end function greeting(name; times = 42, greet = "hello") # println(times, " times ", greet, " to ", name) end julia> greeting("John") 42 times hello to John julia> greeting("Mike", greet = "wassup", times = 100500) # 100500 times wassup to Mike
julia> sqrt sqrt (generic function with 19 methods)
sqrt
is a generic function with 19 methods. What kind of generic function and what methods?sqrt
functions that are applied to different types of arguments and, accordingly, they calculate the square root using different algorithms. See what options there are, by typing julia> methods(sqrt)
julia> @time sqrt(8) # @time - 0.006811 seconds (3.15 k allocations: 168.516 KiB) # , 2.8284271247461903 julia> @time sqrt(15) 0.000002 seconds (5 allocations: 176 bytes) # 5 - @time 3.872983346207417
function mysqrt(num) # - # - if num >= 0 return sqrt(num) else return sqrt(complex(num)) end end function S(n) # sum = 0 sgn = -1 for k = 1:n sum += mysqrt(sgn) sgn = -sgn end return sum end function S_typed(n::Integer) # .. , # sum::Complex = 0.0 sgn::Int = -1 for k = 1:n sum += mysqrt(sgn) sgn = -sgn end return sum end
S_typed()
function not only executes faster, but also does not require memory allocations on every call, unlike S()
. The problem here is that the type of the mysqrt()
returned from mysqrt()
is not defined, as is the type of the right side of the expression sum = sum + mysqrt(sgn)
sum
will be at each iteration. So, boxing (hitch type labels) variable and memory allocation.S_typed()
function, the compiler knows in advance that the sum
is a complex value, so the code is more optimized (in particular, the mysqrt()
call can be effectively zainlaynit, leading the return value to always Complex
).S_typed()
compiler knows that the return value is of type Complex
, but for S()
type of output value is not defined again, which will slow down all functions where S()
will be called.@code_warntype
: julia> @code_warntype S(3) Body::Any # , ... julia> @code_warntype S_typed(3) Body::Complex{Float64} # ...
@code_warntype
cannot deduce the returned type, or for which it is in the body somewhere, it shows the receipt of the Any
value - then optimizing these calls will most likely give a very noticeable performance increase.struct
: julia> struct GenericStruct # struct name b::Int c::Char v::Vector end # # , julia> s = GenericStruct("Name", 1, 'z', [3., 0]) GenericStruct("Name", 1, 'z', [3.0, 0.0]) julia> s.name, sb, sc, sv ("Name", 1, 'z', [3.0, 0.0])
sv
in the example above, can be changed). Mutable structures are created by the mutable struct
construction, the syntax of which is the same as for ordinary structures.A<:B
(A - subtype B) and A>:B
(A - supertype B). It looks like this: abstract type NDimPoint end # - # , - N struct PointScalar<:NDimPoint x1::Real end struct Point2D<:NDimPoint x1::Real x2::Real end struct Point3D<:NDimPoint x1::Real x2::Real x3::Real end # ; Markdown """ mag(p::NDimPoint) Calculate the magnitude of the radius vector of an N-dimensional point `p` """ function mag(p::NDimPoint) sqrmag = 0.0 # .. , # T fieldnames(T) for name in fieldnames(typeof(p)) sqrmag += getfield(p, name)^2 end return sqrt(sqrmag) end """ add(p1::T, p2::T) where T<:NDimPoint Calculate the sum of the radius vectors of two N-dimensional points `p1` and `p2` """ function add(p1::T, p2::T) where T<:NDimPoint # - , .. # list comprehension sumvector = [Float64(getfield(p1, name) + getfield(p1, name)) for name in fieldnames(T)] # , # ... , .. # f([1, 2, 3]...) - , f(1, 2, 3) return T(sumvector...) end
abstract type AbstractPolynomial end """ Polynomial <: AbstractPolynomial Polynomials written in the canonical form """ struct Polynomial<:AbstractPolynomial degree::Int coeff::NTuple{N, Float64} where N # NTuple{N, Type} - N end """ evpoly(p::Polynomial, z::Real) Evaluate polynomial `p` at `z` using the Horner's rule """ function evpoly(p::Polynomial, z::Real) ans = p.coeff[end] for idx = p.degree:-1:1 ans = p.coeff[idx] + z * ans end return ans end
""" InterpPolynomial <: AbstractPolynomial Interpolation polynomials in Newton's form """ struct InterpPolynomial<:AbstractPolynomial degree::Int xval::NTuple{N, Float64} where N coeff::NTuple{N, Float64} where N end """ evpoly(p::Polynomial, z::Real) Evaluate polynomial `p` at `z` using the Horner's rule """ function evpoly(p::InterpPolynomial, z::Real) ans = p.coeff[p.degree+1] for idx = p.degree:-1:1 ans = ans * (z - p.xval[idx]) + p.coeff[idx] end return ans end
evpoly()
- but it takes different types of arguments.InterpPolynomial
type InterpPolynomial
at least be correctly processed by the evpoly()
function. """ Polynomial <: AbstractPolynomial Polynomials written in the canonical form --- Polynomial(v::T) where T<:Union{Vector{<:Real}, NTuple{<:Any, <:Real}}) Construct a `Polynomial` from the list of the coefficients. The coefficients are assumed to go from power 0 in the ascending order. If an empty collection is provided, the constructor returns a zero polynomial. """ struct Polynomial<:AbstractPolynomial degree::Int coeff::NTuple{N, Float64} where N function Polynomial(v::T where T<:Union{Vector{<:Real}, NTuple{<:Any, <:Real}}) # / P(x) ≡ 0 coeff = isempty(v) ? (0.0,) : tuple([Float64(x) for x in v]...) # - new # - return new(length(coeff)-1, coeff) end end """ InterpPolynomial <: AbstractPolynomial Interpolation polynomials in Newton's form --- InterpPolynomial(xsample::Vector{<:Real}, fsample::Vector{<:Real}) Construct an `InterpPolynomial` from a vector of points `xsample` and corresponding function values `fsample`. All values in `xsample` must be distinct. """ struct InterpPolynomial<:AbstractPolynomial degree::Int xval::NTuple{N, Float64} where N coeff::NTuple{N, Float64} where N function InterpPolynomial(xsample::X, fsample::F) where {X<:Union{Vector{<:Real}, NTuple{<:Any, <:Real}}, F<:Union{Vector{<:Real}, NTuple{<:Any, <:Real}}} # , , f , if !allunique(xsample) throw(DomainError("Cannot interpolate with duplicate X points")) end N = length(xsample) if length(fsample) != N throw(DomainError("Lengths of X and F are not the same")) end coeff = [Float64(f) for f in fsample] # (Stoer, Bulirsch, Introduction to Numerical Analysis, . 2.1.3) for i = 2:N for j = 1:(i-1) coeff[i] = (coeff[j] - coeff[i]) / (xsample[j] - xsample[i]) end end new(N-1, tuple([Float64(x) for x in xsample]...), tuple(coeff...)) end end
a + b
and +(a, b)
are both valid and absolutely identical), their overload is done in the same way as writing additional methods to its functions.Main
, and the functions of the standard library are in the Base
module, so when overloaded, you must either import the Base
module or write the full name of the function. # - Base.+ , # Base.:+, " :+ Base" function Base.:+(p::Polynomial, x::Real) Polynomial(tuple(p.coeff[1] + x, p.coeff[2:end]...)) end function Base.:+(p::InterpPolynomial, x::Real) # .. - # . # - # fval::Vector{Float64} = [evpoly(p, xval) + x for xval in p.xval] InterpPolynomial(p.xval, fval) end # function Base.:+(x::Real, p::AbstractPolynomial) return p + x end
function Base.:+(p1::Polynomial, p2::Polynomial) # , deg = max(p1.degree, p2.degree) coeff = zeros(deg+1) coeff[1:p1.degree+1] .+= p1.coeff coeff[1:p2.degree+1] .+= p2.coeff Polynomial(coeff) end function Base.:+(p1::InterpPolynomial, p2::InterpPolynomial) xmax = max(p1.xval..., p2.xval...) xmin = min(p1.xval..., p2.xval...) deg = max(p1.degree, p2.degree) dx = xmax - xmin # # chebgrid = zeros(deg+1) for k = 1:deg-1 chebgrid[k+1] = xmax - 0.5 * dx * (1 + cos((k - 0.5) * π / (deg - 1))) end chebgrid[1] = xmin chebgrid[end] = xmax fsample = [evpoly(p1, x) + evpoly(p2, x) for x in chebgrid] InterpPolynomial(chebgrid, fsample) end function Base.:+(p1::InterpPolynomial, p2::Polynomial) xmax = max(p1.xval...) xmin = min(p1.xval...) deg = max(p1.degree, p2.degree) dx = xmax - xmin chebgrid = zeros(deg+1) for k = 1:deg-1 chebgrid[k+1] = xmax - 0.5 * dx * (1 + cos((k - 0.5) * π / (deg - 1))) end chebgrid[1] = xmin chebgrid[end] = xmax fsample = [evpoly(p1, x) + evpoly(p2, x) for x in chebgrid] InterpPolynomial(chebgrid, fsample) end function Base.:+(p1::Polynomial, p2::InterpPolynomial) p2 + p1 end
Source: https://habr.com/ru/post/450628/
All Articles