0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Julia 特殊な値 nothing missing NaN Inf について

Last updated at Posted at 2022-12-04

nothing missing Nan Inf

Juliaには、特殊な値を表すためにいくつかの組み込み定数が用意されています。

  • nothing: この定数は、値が存在しないことを示すものです。
  • missing: この定数は、値が存在するが不明であることを示すものです。
  • NaN: この定数は、数値が不正であることを示すものです。例えば、0で割る演算や無限大の値を計算する演算では、この定数が返されます。
  • Inf: この定数は、正の無限大を表すものです。負の無限大は、-Infと表現します。

以下は、これらの組み込み定数を使ったプログラムの例です。

# nothing
x = nothing

# missing
y = missing

# NaN
z = 0 / 0

# Inf
w = 1 / 0

println("x = $x")
println("y = $y")
println("z = $z")
println("w = $w")

x = nothing
y = missing
z = NaN
w = Inf

nothing と 未定義

notingは空を意味しますが、変数そのものは存在します。
未定義の場合変数そのものも存在しません。

以下は未定義の変数を使ってしまった場合です。エラーが発生します。

#変数abcは未定義
println(abc)

# UndefVarError: abc not defined

変数として予約したい場合などにnotingを使います。

判定

組込み定数nothing、missing、NaN、Infを判定するための組み込み関数が用意されています。それらの関数は、次のように使用します。

# nothing
isnothing(x)

# missing
ismissing(x)

# NaN
isnan(x)

# Inf
isinf(x)

xには、判定したい値を指定します。各関数は、指定された値がその組み込み定数の場合はtrueを、そうでない場合はfalseを返します。

以下は、これらの組み込み関数を使ったプログラムの例です。

# nothing
x = nothing
println(isnothing(x)) # true

# missing
y = missing
println(ismissing(y)) # true

# NaN
z = 0 / 0
println(isnan(z)) # true

# Inf
w = 1 / 0
println(isinf(w)) # true

このプログラムを実行すると、次のようになります。

# 出力
true
true
true
true

組み込み定数を使用することで、値が特殊な値であるかどうかを判定することができます。

参考図書

1から始めるプログラミング

Juliaプログラミングクックブック

天才プログラマー タンメイが教える Julia超入門

0
1
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?