LoginSignup
0
1

More than 1 year has passed since last update.

Juliaで"."(ドット)を使ってブロードキャストする

Last updated at Posted at 2022-12-31

Julia独特の表記(?)で慣れずに何度も忘れたのでメモしておく。

以下のような配列があったとする。

julia> a = [1,2,3]
3-element Vector{Int64}:
 1
 2
 3

この配列の要素全てに計算を行いたい(ブロードキャストしたい)場合は,演算子に.を加える。

加算(addition)

julia> a .+ 1
3-element Vector{Int64}:
 2
 3
 4

減算(substraction)

julia> a .- 1
3-element Vector{Int64}:
 0
 1
 2

乗算(multiplication)

julia> a .*2
3-element Vector{Int64}:
 2
 4
 6

除算(division)

julia> a ./2
3-element Vector{Float64}:
 0.5
 1.0
 1.5

累乗(division)

julia> a .^2
3-element Vector{Int64}:
 1
 4
 9

除算の商(quotient)

julia> a2
3-element Vector{Int64}:
 0
 1
 1

ちなみにMacで÷をタイプするにはoption+/

剰余(remainder)

julia> a .%2
3-element Vector{Int64}:
 1
 0
 1

等価(equal)

julia> a .==2
3-element BitVector:
 0
 1
 0

小なりイコール(less than or equal to)

julia> a .≤ 2
3-element BitVector:
 1
 1
 0

Macでをタイプするにはoption+<

実は乗算と除算はドットがなくてもブロードキャスト可能

@WolfMoon さんから教えていただきました。

julia> a *2
3-element Vector{Int64}:
 2
 4
 6
julia> a /2
3-element Vector{Float64}:
 0.5
 1.0
 1.5

おまけ Pythonのnumpyの場合

ちなみにPythonのnumpyの場合は自動でブロードキャストされる。

>>> import numpy as np
>>> a = np.array([1,2,3])
>>> a+1
array([2, 3, 4])
0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1