<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>「arctan」タグの記事一覧Python Tech</title>
	<atom:link href="https://tech.nkhn37.net/tag/arctan/feed/" rel="self" type="application/rss+xml" />
	<link>https://tech.nkhn37.net</link>
	<description>Python学習サイト</description>
	<lastBuildDate>Sun, 11 Jan 2026 21:11:10 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://tech.nkhn37.net/wp-content/uploads/2021/01/cropped-lion-normal-clear-1-32x32.png</url>
	<title>「arctan」タグの記事一覧Python Tech</title>
	<link>https://tech.nkhn37.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【NumPy】ユニバーサル関数（ufuncs）を用いた配列（ndarray）の計算</title>
		<link>https://tech.nkhn37.net/numpy-ufuncs-ndarray-calculation/</link>
					<comments>https://tech.nkhn37.net/numpy-ufuncs-ndarray-calculation/#respond</comments>
		
		<dc:creator><![CDATA[naoki-hn]]></dc:creator>
		<pubDate>Sun, 26 Dec 2021 00:00:00 +0000</pubDate>
				<category><![CDATA[NumPy]]></category>
		<category><![CDATA[add]]></category>
		<category><![CDATA[arccos]]></category>
		<category><![CDATA[arcsin]]></category>
		<category><![CDATA[arctan]]></category>
		<category><![CDATA[cos]]></category>
		<category><![CDATA[divide]]></category>
		<category><![CDATA[floor_divide]]></category>
		<category><![CDATA[log]]></category>
		<category><![CDATA[mod]]></category>
		<category><![CDATA[multiply]]></category>
		<category><![CDATA[ndarray]]></category>
		<category><![CDATA[negative]]></category>
		<category><![CDATA[power]]></category>
		<category><![CDATA[sin]]></category>
		<category><![CDATA[subtract]]></category>
		<category><![CDATA[tan]]></category>
		<category><![CDATA[ufuncs]]></category>
		<guid isPermaLink="false">https://tech.nkhn37.net/?p=2088</guid>

					<description><![CDATA[NumPyのユニバーサル関数（universal functions: ufuncs）の概要を紹介をします。 ユニバーサル関数（ufuncs）概要 NumPyのユニバーサル関数とは、NumPyの配列（ndarray）の演 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">NumPyの<span class="marker"><strong>ユニバーサル関数（universal functions: ufuncs）の概要</strong></span>を紹介をします。</p>



<h2 class="wp-block-heading jinr-heading d--bold" id="ユニバーサル関数-ufuncs-概要">ユニバーサル関数（ufuncs）概要</h2>



<p class="wp-block-paragraph">NumPyの<span class="marker"><strong>ユニバーサル関数</strong></span>とは、NumPyの配列（ndarray）の演算のための関数です。universal functionsを省略して<span class="marker"><strong>ufuncs</strong></span>とも呼ばれます。</p>



<p class="wp-block-paragraph">本記事ではユニバーサル関数の特徴とユニバーサル関数の例を紹介をします。</p>



<h3 class="wp-block-heading jinr-heading d--bold" id="ユニバーサル関数-ufuncs-は演算が高速">ユニバーサル関数（ufuncs）は演算が高速</h3>



<p class="wp-block-paragraph">ユニバーサル関数（ufuncs）は、Pythonのリストをでの演算と比べて高速であるという特徴があります。</p>



<p class="wp-block-paragraph">では、具体的にPythonのリストでの数値演算処理とNumPyのユニバーサル関数（ufuncs）での数値演算処理がどの程度違うのかを比較していきたいと思います。</p>



<h4 class="wp-block-heading jinr-heading d--bold" id="pythonのリストのループは遅い">Python組み込みのリストを使ったループは遅い</h4>



<p class="wp-block-paragraph">Python組み込みのリストの各要素を指定した数値で割った数値を計算するという簡単な例を考えてみます。以下の簡単なプログラムを実行してみてください。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
import time


def measure_execution_time(func):
    def wrapper(*args, **kwargs):
        # 処理前の時刻を設定
        timer_start = time.time()
        # 対象関数の実行
        result = func(*args, **kwargs)
        # 処理後の時刻を設定
        timer_end = time.time()
        # 処理時間を計算
        elapsed_time = timer_end - timer_start
        print(f'処理実行時間: {elapsed_time} sec')
        return result
    return wrapper


@measure_execution_time
def calculate_div(values, div_num):
    """ 入力値を指定値で割る
    :param values: 対象配列
    :param div_num: 割る数
    :return: 対象配列の各要素をdiv_numで割った配列
    """
    output_array = np.empty(len(values))

    for i in range(len(values)):
        output_array[i] = values[i] / div_num

    return output_array


def main():
    np.random.seed(1)

    div_num = 2
    data_size = 10000
    values = np.random.randint(0, 10, data_size)
    print(f'values: {values}')

    result = calculate_div(values, div_num)
    print(result)


if __name__ == '__main__':
    main()
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果例】data_size=10000
values: [5 8 9 ... 5 3 5]
処理実行時間: 0.003020763397216797 sec
[2.5 4.  4.5 ... 2.5 1.5 2.5]</pre>



<p class="wp-block-paragraph">上記はdata_size=10000のランダムなリストを生成し、各要素を2で割るという処理をしています。今回作成した関数calculate_divは内部でforの繰り返し処理で各要素の割り算を実行しています。</p>



<p class="wp-block-paragraph">実行結果例は私のPCでの実行結果のため、パソコンのスペックにより時間は異なるかと思います。data_sizeについては皆さんお使いの環境にあわせて調整してみてください。</p>



<p class="wp-block-paragraph">ここで試してもらいたいのは、data_sizeをどんどん大きな値にしてみてもらいたいという点です。以下はdata_sizeを100,000,000（1億）にして試してみた結果です。こちらも皆さんのPCのスペックにより時間は異なると思うので少しずつ件数を増やしながら確認してみてください。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果例】data_size=100000000
values: [5 8 9 ... 1 9 5]
処理実行時間: 22.246026754379272 sec
[2.5 4.  4.5 ... 0.5 4.5 2.5]</pre>



<p class="wp-block-paragraph">処理速度が非常に遅くなってしまっていることが分かります。Pythonは動的型付けのプログラミング言語で柔軟性が高く、listの各要素を別の型に設定するようなこともできます。</p>



<p class="wp-block-paragraph">この動的型付けは各要素がどの型かを確認するようなオーバーヘッド処理が含まれることを意味しているため、どうしても処理が遅くなってしまいます。</p>



<p class="wp-block-paragraph">話の流れ的にもうお気づきかと思いますが、NumPyを使用すると同様の処理を非常に高速に処理することができます。</p>



<h4 class="wp-block-heading jinr-heading d--bold" id="numpyのユニバーサル関数はベクトル計算で高速">NumPyのユニバーサル関数はベクトル計算で高速</h4>



<p class="wp-block-paragraph">NumPyの演算はユニバーサル関数（ufuncs）として定義されており、演算はベクトル演算として処理されます。</p>



<p class="wp-block-paragraph">ベクトル演算では、例えば $\boldsymbol{x}$がベクトルであった時に$\boldsymbol{y}=2\times\boldsymbol{x}$とすると、$\boldsymbol{y}$は$\boldsymbol{x}$の各要素を2倍したベクトルになります。</p>



<p class="wp-block-paragraph">NumPyのユニバーサル関数では例えば「y=2*x」というような自然なコードで上記のようなベクトル演算ができます。</p>



<p class="wp-block-paragraph">では、先ほどの例のcalculate_divの部分を以下のように置き換えて実行してみてください。件数は、data_sizeを100,000,000（1億）にして実行してみます。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def calculate_div(values, div_num):
    """ 入力値を指定値で割る
    :param values: 対象配列
    :param div_num: 割る数
    :return: 対象配列の各要素をdiv_numで割った配列
    """
    output_array = values / div_num
    return output_array</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果例】data_size=100000000
values: [5 8 9 ... 1 9 5]
処理実行時間: 0.15458941459655762 sec
[2.5 4.  4.5 ... 0.5 4.5 2.5]</pre>



<p class="wp-block-paragraph">Pythonの組み込みlistのループ処理では20秒以上かかっていた処理が、なんと0.15秒という速度で返ってきていることが分かります。</p>



<p class="wp-block-paragraph">上記のような処理の背景にある関連内容として「<span class="marker"><strong>ブロードキャスト（Broadcast）</strong></span>」というものがあります。これは異なるサイズのもののサイズをそろえて処理する機能のことでユニバーサル関数の動作の土台となる機能です。「<a href="https://tech.nkhn37.net/numpy-broadcasting-basic/" target="_blank" rel="noreferrer noopener">ブロードキャスト（broadcast）の基本</a>」に基本的な考え方をまとめていますので参考にしてください。</p>



<p class="wp-block-paragraph">ここでは、<span class="marker"><strong>ユニバーサル関数が大きなサイズの演算にも高速に対応できる</strong></span>ということを理解いただければと思います。</p>



<section class="wp-block-jinr-blocks-iconbox b--jinr-block b--jinr-iconbox"><div class="d--simple-iconbox5 ">
			<i class="jif jin-ifont-v2speaker" aria-hidden="true"></i>
			<div class="a--jinr-iconbox">
<p class="wp-block-paragraph">今回は簡単なデコレーターで処理を確認してみましたが、以下のように IPython のマジックコマンドを用いると簡単に処理時間を調べることができます。</p>



<p class="wp-block-paragraph">以下のように IPython コンソールを実行して、<code>%timeit</code> をつけて以下のような処理を実行してみてください。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
def calculate_div(values, div_num):
    output_array = values / div_num
    return output_array
np.random.seed(1)
div_num = 2
data_size = 100000000
values = np.random.randint(0, 10, data_size)
%timeit calculate_div(values, div_num)</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果例】
197 ms ± 986 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)</pre>



<p class="wp-block-paragraph">IPython での実行では、該当箇所を繰り返し実行した平均と標準偏差を出してくれるのでより正確に処理時間が分かります。</p>
</div>
		</div></section>



<h2 class="wp-block-heading jinr-heading d--bold" id="各種ユニバーサル関数-ufuncs-の例">各種ユニバーサル関数（ufuncs）の例</h2>



<p class="wp-block-paragraph">ユニバーサル関数の特徴について上記で見てきました。以降では、NumPyの具体的なユニバーサル関数の例を見ていきます。</p>



<h3 class="wp-block-heading jinr-heading d--bold" id="数値計算">数値計算</h3>



<p class="wp-block-paragraph">NumPyの数値計算のユニバーサル関数は、pythonでもともと用意されている数値計算の演算子と同じなのでとても直感的に使うことができます。</p>



<p class="wp-block-paragraph">代表的な数値計算は以下の通りです。「x+1」等のように感覚的に使用することができます。また、それぞれの演算子と関数が紐づいているためnp.add(x, 1)のように使用しても構いません。</p>



<figure class="wp-block-table"><table><thead><tr><th>演算子</th><th>ユニバーサル関数（ufuncs）</th><th>説明</th></tr></thead><tbody><tr><td>+</td><td>np.add</td><td>加算（例：1 + 1 = 2）</td></tr><tr><td>&#8211;</td><td>np.subtract</td><td>減算（例：2 &#8211; 1 = 1）</td></tr><tr><td>*</td><td>np.multiply</td><td>乗算（例：2 * 5 = 10）</td></tr><tr><td>/</td><td>np.divide</td><td>除算（例：5 / 2 = 2.5）</td></tr><tr><td>**</td><td>np.power</td><td>累乗（例：2 ** 3 = 8）</td></tr><tr><td>//</td><td>np.floor_divide</td><td>切り捨て除算（例：5 // 2 = 2）</td></tr><tr><td>%</td><td>np.mod</td><td>剰余（例：5 % 2 = 1）</td></tr><tr><td>&#8211;</td><td>np.negative</td><td>マイナス（例：-2）</td></tr></tbody></table></figure>



<h3 class="wp-block-heading jinr-heading d--bold" id="三角関数">三角関数</h3>



<p class="wp-block-paragraph">他にもよく使用する関数として三角関数があります。代表的な三角関数は以下の通りです。</p>



<figure class="wp-block-table"><table><thead><tr><th>ユニバーサル関数（ufuncs）</th><th>説明</th></tr></thead><tbody><tr><td>np.sin</td><td>sin関数</td></tr><tr><td>np.cos</td><td>cos関数</td></tr><tr><td>np.tan</td><td>tan関数</td></tr><tr><td>np.arcsin</td><td>sinの逆関数</td></tr><tr><td>np.arccos</td><td>cosの逆関数</td></tr><tr><td>np.arctan</td><td>tanの逆関数</td></tr></tbody></table></figure>



<section class="wp-block-jinr-blocks-iconbox b--jinr-block b--jinr-iconbox"><div class="d--simple-iconbox6 ">
			<i class="jif jin-ifont-v2books" aria-hidden="true"></i>
			<div class="a--jinr-iconbox">
<p class="wp-block-paragraph">上記は数値計算や三角関数の一部を紹介したものなります。他にも NumPy にはたくさんのユニバーサル関数があります。</p>



<p class="wp-block-paragraph">NumPy のユニバーサル関数については、公式ドキュメントの<a href="https://numpy.org/doc/stable/reference/ufuncs.html" target="_blank" rel="noreferrer noopener">こちら</a>を参照してください。。</p>
</div>
		</div></section>


<section class="b--jinr-block b--jinr-blogcard d--blogcard-hover-up d--blogcard-style1 d--blogcard-mysite t--round "><div class="a--blogcard-label ef">あわせて読みたい</div><a class="o--blogcard-link t--round" href="https://tech.nkhn37.net/python-tech-summary-page/"><div class="c--blogcard-image"><img decoding="async" class="a--blogcard-img-src" width="128" height="72" src="https://tech.nkhn37.net/wp-content/uploads/2024/08/Python-Tech-Pythonプログラミングガイド_new1-640x360.jpg" alt="【Python Tech】プログラミングガイド" /></div><div class="a--blogcard-title d--bold">【Python Tech】プログラミングガイド</div></a></section>]]></content:encoded>
					
					<wfw:commentRss>https://tech.nkhn37.net/numpy-ufuncs-ndarray-calculation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Disk: Enhanced  を使用したページ キャッシュ

Served from: tech.nkhn37.net @ 2026-06-22 00:05:06 by W3 Total Cache
-->