1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonからJuliaを呼び出して積分を計算する方法

Posted at

はじめに

本記事では、PythonからJuliaを呼び出して積分を計算する方法と、Pythonのみで積分を行う方法の両方を解説します。

特に以下のような方におすすめです:

  • Python環境からJuliaの数値計算ライブラリを使いたい方
  • PythonとJuliaのハイブリッド活用に興味がある方
  • 数値積分(例:$\int_0^1 x^2 dx$)をPythonとJuliaの両方で比較したい方

本記事では、実際に動くコードとその実行結果を交えながら、シンプルかつ実用的な形で解説していきます。

それでは、まずPythonコードの全体像からご紹介します。


Pythonコード

from julia import Julia
jl = Julia(compiled_modules=False)

from julia import Main
from scipy import integrate

# --- Julia側で数値積分(∫₀¹ x² dx) ---
Main.eval("""
import Pkg
Pkg.add("QuadGK")
""")

Main.eval("""
using QuadGK
result, err = quadgk(x -> x^2, 0, 1)
""")

# Juliaから結果取得
julia_result = Main.eval("result")
julia_error = Main.eval("err")

print(f"[Julia] Integral of x^2 from 0 to 1 = {julia_result:.6f} (error estimate: {julia_error:.2e})")

# --- Python側で数値積分 ---
def f(x):
    return x**2

python_result, python_error = integrate.quad(f, 0, 1)

print(f"[Python] Integral of x^2 from 0 to 1 = {python_result:.6f} (error estimate: {python_error:.2e})")

結果

[Julia] Integral of x^2 from 0 to 1 = 0.333333 (error estimate: 0.00e+00)
[Python] Integral of x^2 from 0 to 1 = 0.333333 (error estimate: 3.70e-15

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?