0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

合格(うか)る計算数学 I・A・II・BのためのPythonベースのアジャイルソリューション

Last updated at Posted at 2025-03-25

(仮)

はじめに

近年の大学入試では、思考力・表現力に加え、「ミスなく迅速に処理する計算力」が依然として高く問われています。特に数学I・A・II・Bでは、数式処理・グラフ描写・場合の数やベクトルなど、多様な分野における正確な演算スキルが不可欠です。

しかし、従来の学習法では次のような課題も存在します。

  • 手を動かす反復が多く、効率が悪い
  • 間違いの原因分析が難しい
  • 教材の視覚化・即時フィードバックに限界

こうした課題を、PythonとマルチモーダルなChatGPTが解決へと導きます。

本プロジェクトの中核:汎用化・集積化されたデジタル回路により、ITで寄り添う計算ソリューション

『合格(うか)る計算数学 I・A・II・B』は、Pythonコードと対話型AI(ChatGPT)を融合した次世代型の数学学習支援DXプラットフォームとなりました。
学習者一人ひとりに寄り添い、理解の深化と自律的な学びを後押しします。
さあ、皆様さんもデジタルと教育の融合で、AIを活用したリカレント教育の未来をともに加速していきましょう!

特徴

  • 汎用性ある問題設計:大学入試で出題される形式を抽象化し、Pythonコードで自動計算・可視化
  • 寄り添うフィードバック:ChatGPTが途中式や間違いの要因まで解説し、一人ひとりの理解の深さに応じて対応
  • アジャイルな会話型学習:疑問が出た瞬間に対話しながら計算式・グラフ・ベクトルを扱える

実行環境:Python + Google Colab + ChatGPT

Python導入解説動画

Pythonで始める学びの自動化

Google Colab 環境構築ガイド

ブラウザだけでPythonが動く!Colab講座

マルチモーダルChatGPTとの連携活用

図・表・コードもOK!マルチモーダルChatGPT

使い方

この後に貼り付ける Python コードは、Google Colab にそのままコピー&ペーストして実行可能です。
マルチモーダル対応の ChatGPT と連携することで、以下のような多様な目的に対応できます:

アルゴリズムや数式の構造的な理解

Python を使ったロジックの検証と確認

ビジネスパーソンとしての英語力・専門用語の習得

さらに、高校数学の本質的な理解をAIの力で加速させることで、
大学レベルの数学的課題にも柔軟に対応できる基礎力強化ソリューションの提供が可能となっています。
これは、教育におけるDX(デジタルトランスフォーメーション)を本質から推進する取り組みです。

私たちは、「正解を教える」のではなく、アジャイルな対話と継続的なフィードバックループを通じて、
ともに**“進化し続ける学びのプロセス”**を実現していきます。

お客様に提供する「約数を見つけ方1」ソリューション

import math  # 数学関数を使うためのライブラリ / Import math library for mathematical functions

# Aの設定 / Define the value of A
A = 40000

# Aの約数を求める / Find all divisors of A
divisors = [i for i in range(1, A + 1) if A % i == 0]

# √A を B√C の形に簡単化する関数 / Function to simplify sqrt(A) into B√C form
def simplify_sqrt(n):
    B = 1
    C = n
    # √n から1まで調べて、最大の平方数で割れるものを探す / Find the largest square factor
    for i in range(int(math.sqrt(n)), 0, -1):
        if n % (i * i) == 0:
            B = i
            C = n // (i * i)
            break
    return B, C

# √A を B√C の形に変換 / Convert sqrt(A) into simplified form
B, C = simplify_sqrt(A)

# 結果の表示 / Print results
print(f"A = {A}")
print(f"A の約数 / Divisors of A: {divisors}")
print(f"{A} = {B}{C}")

# C の約数を求める / Find divisors of C
divisors_C = [i for i in range(1, C + 1) if C % i == 0]

# C の約数を表示 / Print divisors of C
print(f"C = {C} の約数 / Divisors of C: {divisors_C}")

お客様に提供する「素因数分解2」ソリューション

# 約数を求める関数
def find_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5) + 1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n // i)
    divisors.sort()  # 約数を昇順でソート
    return divisors

# 1から50までのNに対して計算を行う
for N in range(1, 51):
    # N^N, 2^N, 3^N, 5^Nを計算
    n_power_n = N ** N
    two_power_n = 2 ** N
    three_power_n = 3 ** N
    five_power_n = 5 ** N
    
    # Nの約数を計算
    divisors = find_divisors(N)
    
    # 結果を表示
    print(f"N = {N}: N^N = {n_power_n}, 2^N = {two_power_n}, 3^N = {three_power_n}, 5^N = {five_power_n}, Nの約数 = {divisors}")


お客様に提供する「最大公約数3」ソリューション

import math  # mathライブラリをインポート(gcd計算に使用)/ Import math library for gcd calculation

# 最大公約数 (GCD) と最小公倍数 (LCM) を求める関数
# Function to compute the Greatest Common Divisor (GCD) and Least Common Multiple (LCM)
def gcd_lcm(a, b, c=None):
    # 2つの数の場合 / If only two numbers are given
    if c is None:
        gcd = math.gcd(a, b)  # 最大公約数 / Greatest Common Divisor
        lcm = abs(a * b) // gcd  # 最小公倍数 / Least Common Multiple
        print(f"2つの数 ({a}, {b}) の最大公約数: {gcd} / GCD of ({a}, {b}): {gcd}")
        print(f"2つの数 ({a}, {b}) の最小公倍数: {lcm} / LCM of ({a}, {b}): {lcm}")
    
    # 3つの数の場合 / If three numbers are given
    else:
        # ステップ1: 最初の2つの最大公約数 / Step 1: GCD of first two numbers
        gcd_ab = math.gcd(a, b)
        # ステップ2: 3つ目も含めた最大公約数 / Step 2: GCD of all three numbers
        gcd_abc = math.gcd(gcd_ab, c)

        # ステップ1: 最初の2つの最小公倍数 / Step 1: LCM of first two numbers
        lcm_ab = abs(a * b) // gcd_ab
        # ステップ2: 3つ目も含めた最小公倍数 / Step 2: LCM of all three numbers
        lcm_abc = abs(lcm_ab * c) // math.gcd(lcm_ab, c)

        print(f"3つの数 ({a}, {b}, {c}) の最大公約数: {gcd_abc} / GCD of ({a}, {b}, {c}): {gcd_abc}")
        print(f"3つの数 ({a}, {b}, {c}) の最小公倍数: {lcm_abc} / LCM of ({a}, {b}, {c}): {lcm_abc}")

# 例として2つと3つの数の最大公約数と最小公倍数を計算
# Example calculations for GCD and LCM of 2 and 3 numbers
gcd_lcm(12, 18)
gcd_lcm(12, 18, 24)

import math
import pandas as pd

# ユークリッドの互除法と拡張互除法(x, y も求める)
def extended_euclidean(a, b):
    steps = []
    old_r, r = a, b
    old_s, s = 1, 0
    old_t, t = 0, 1

    while r != 0:
        q = old_r // r
        steps.append([old_r, r, q, old_r % r])
        old_r, r = r, old_r - q * r
        old_s, s = s, old_s - q * s
        old_t, t = t, old_t - q * t

    return old_r, old_s, old_t, steps  # gcd, x, y, step list

# 例題:275x + 61y = 1 を解く
a = 275
b = 61

# 互除法を実行
gcd_val, x0, y0, steps = extended_euclidean(a, b)

# DataFrameとしてステップを表示
df = pd.DataFrame(steps, columns=["a", "b", "商 q", "余り r"])
print("▼ ユークリッドの互除法のステップ")
print(df)

# 結果の表示
print("\n▼ 拡張ユークリッドの互除法の結果")
print(f"{a}{b} の最大公約数: {gcd_val}")
print(f"{a}×({x0}) + {b}×({y0}) = {gcd_val}")

# 1次不定方程式の一般解を表示
print("\n▼ 1次不定方程式の一般解(すべての整数解)")
print(f"x = {x0} + {b}k")
print(f"y = {y0} - {a}k")
print("(k は任意の整数)")

お客様に提供する「N進数7」ソリューション

# 10進数を2進数に変換(2ビットに収める)
def decimal_to_binary(n, bits=2):
    binary = bin(n)[2:]  # 2進数に変換し、'0b' を除去
    return binary.zfill(bits)  # 2ビットにパディング

# 2進数を10進数に変換
def binary_to_decimal(b):
    return int(b, 2)

# 二分探索 (2ビットを探索)
def binary_search(arr, target):
    low = 0
    high = len(arr) - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == target:
            return mid  # 見つかった位置
        elif arr[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1  # 見つからない場合

# 例として10進数を2進数に変換、2進数を10進数に変換、2ビットで二分探索を実行
decimal_num = 3
binary_num = decimal_to_binary(decimal_num, bits=2)
print(f"10進数 {decimal_num} を2進数に変換: {binary_num}")

binary_num = '11'  # 2進数
decimal_num_converted = binary_to_decimal(binary_num)
print(f"2進数 {binary_num} を10進数に変換: {decimal_num_converted}")

# 二分探索の例(2ビットのリスト)
arr = ['00', '01', '10', '11']  # 2ビットのリスト
target = '10'
result = binary_search(arr, target)
if result != -1:
    print(f"ターゲット {target} はインデックス {result} にあります。")
else:
    print(f"ターゲット {target} はリストにありません。")

お客様に提供する「筆算ケイサン8」ソリューション

import numpy as np
import matplotlib.pyplot as plt
from itertools import product

# ==== 筆算(手計算スタイル)シミュレーション / Vertical multiplication simulation ====
def vertical_multiplication(a, b):
    a_str = str(a)
    b_str = str(b)
    results = []
    for i, digit in enumerate(reversed(b_str)):
        partial = int(digit) * a
        results.append((partial, i))
    final = a * b
    return results, final

# ==== 論理回路:半加算器 / Half Adder ====
def half_adder(a, b):
    sum_bit = a ^ b
    carry = a & b
    return sum_bit, carry

# ==== 論理回路:全加算器 / Full Adder ====
def full_adder(a, b, cin):
    s1, c1 = half_adder(a, b)
    sum_bit, c2 = half_adder(s1, cin)
    carry = c1 | c2
    return sum_bit, carry

# ==== NANDゲート / NAND gate ====
def nand_gate(a, b):
    return int(not (a and b))

# ==== 表示:筆算スタイル / Show vertical multiplication steps ====
a, b = 123, 45
steps, total = vertical_multiplication(a, b)

print("=== Vertical Multiplication ===")
print(f"  {a}")
print(f"x {b}")
print("------")
for val, shift in steps:
    print(" " * shift + str(val))
print("------")
print(f"{total}")

# ==== 表示:半加算器と全加算器の真理値表 / Truth tables ====
print("\n=== Half Adder Truth Table ===")
print("A B | SUM CARRY")
for a, b in product([0, 1], repeat=2):
    s, c = half_adder(a, b)
    print(f"{a} {b} |  {s}    {c}")

print("\n=== Full Adder Truth Table ===")
print("A B Cin | SUM CARRY")
for a, b, cin in product([0, 1], repeat=3):
    s, c = full_adder(a, b, cin)
    print(f"{a} {b}  {cin}  |  {s}    {c}")

print("\n=== NAND Gate Truth Table ===")
print("A B | OUT")
for a, b in product([0, 1], repeat=2):
    out = nand_gate(a, b)
    print(f"{a} {b} |  {out}")

# ==== 回路図プロット / Draw symbolic circuit diagram ====
fig, ax = plt.subplots(figsize=(10, 5))
ax.axis('off')

# 半加算器ブロック / Half Adder block
ax.text(0.1, 0.6, "Half Adder", fontsize=12, bbox=dict(facecolor='skyblue', edgecolor='black'))
ax.text(0.05, 0.65, "A")
ax.text(0.05, 0.55, "B")
ax.text(0.25, 0.65, "SUM")
ax.text(0.25, 0.55, "CARRY")

# 全加算器ブロック / Full Adder block
ax.text(0.6, 0.6, "Full Adder", fontsize=12, bbox=dict(facecolor='lightgreen', edgecolor='black'))
ax.text(0.55, 0.68, "A")
ax.text(0.55, 0.60, "B")
ax.text(0.55, 0.52, "Cin")
ax.text(0.75, 0.68, "SUM")
ax.text(0.75, 0.60, "CARRY")

# NANDゲートブロック / NAND gate block
ax.text(0.35, 0.3, "NAND Gate", fontsize=12, bbox=dict(facecolor='orange', edgecolor='black'))
ax.text(0.30, 0.35, "A")
ax.text(0.30, 0.25, "B")
ax.text(0.45, 0.30, "OUT")

plt.title("Logic Circuit Blocks: Half Adder, Full Adder, NAND Gate")
plt.show()


お客様に提供する「分母の有理化10」ソリューション


import sympy as sp

# 記号の定義
x = sp.Symbol('x')

# 例1: 1/√2 の有理化
expr1 = 1 / sp.sqrt(2)
rationalized1 = sp.radsimp(expr1)

# 例2: 1/(1 + √3) の有理化
expr2 = 1 / (1 + sp.sqrt(3))
rationalized2 = sp.radsimp(expr2)

# 例3: x / (2 + √x)
expr3 = x / (2 + sp.sqrt(x))
rationalized3 = sp.radsimp(expr3)

# 結果表示
print("【有理化の結果】")
print("1/√2 =", rationalized1)
print("1/(1 + √3) =", rationalized2)
print("x / (2 + √x) =", rationalized3)

お客様に提供する「2重根号11」ソリューション

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# -------------------------------
# 2重根号の定義 / Nested radical
# z = sqrt(1 + sqrt(x^2 + y^2))
# -------------------------------

# x, y の範囲設定
x = np.linspace(-5, 5, 200)
y = np.linspace(-5, 5, 200)
X, Y = np.meshgrid(x, y)

# Z を計算(2重根号)
Z = np.sqrt(1 + np.sqrt(X**2 + Y**2))

# -------------------------------
# 3D プロット
# -------------------------------
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(111, projection='3d')

# サーフェスの描画
surf = ax.plot_surface(X, Y, Z, cmap='viridis', edgecolor='none')

# ラベル設定
ax.set_title(r'$z = \sqrt{1 + \sqrt{x^2 + y^2}}$')
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")

# カラーバー
fig.colorbar(surf, ax=ax, shrink=0.5, aspect=5)

plt.tight_layout()
plt.show()

お客様に提供する「無理数の概算値12」ソリューション

import math

# N の定義
N = 20

# √N を B√C に変換 / Convert √N to B√C
def simplify_sqrt(n):
    for i in range(int(math.sqrt(n)), 0, -1):
        if n % (i * i) == 0:
            B = i
            C = n // (i * i)
            return B, C
    return 1, n  # √n が既約なとき

# 変換
B, C = simplify_sqrt(N)

# 実数値の計算 / Decimal value
sqrt_N = math.sqrt(N)
approx_value = B * math.sqrt(C)

# 結果の表示
print(f"{N} = {B}{C}")
print(f"{N} = ({B}{C})² = {B**2} × {C} = {B**2 * C}")
print(f"{N}{sqrt_N:.10f}")
print(f"{B}{C}{approx_value:.10f}")

お客様に提供する「展開の仕組み13」ソリューション

import sympy as sp

# シンボルの定義 / Define symbolic variable
x = sp.Symbol('x')

# 定数の定義 / Define constants
A = 3
B = -1
C = 10

# 目的関数の定義 / Define objective function
f_expr = (x + A) * (x + B)

# 展開 / Expand the expression
f_expanded = sp.expand(f_expr)

print(f"展開された目的関数: f(x) = {f_expanded}\n")

# -C から C までの x の値に対して計算 / Evaluate from -C to C
print(f"x の値と f(x) の対応(x = -{C}{C}):")
for i in range(-C, C + 1):
    value = f_expanded.subs(x, i)
    print(f"x = {i:>2} → f(x) = {value}")

お客様に提供する「平方完成24」ソリューション

import sympy as sp

# 変数の定義
x, a, b, c = sp.symbols('x a b c')

# a = 3, b = 1, c = 9
a_val = 3
b_val = 1
c_val = 9

# 解の公式を使って文字式で解を求める
discriminant = b**2 - 4*a*c  # 判別式
solution_1 = (-b + sp.sqrt(discriminant)) / (2*a)
solution_2 = (-b - sp.sqrt(discriminant)) / (2*a)

# a, b, cの値を代入して計算
b_squared = b_val**2
four_ac = 4 * a_val * c_val
discriminant_value = b_squared - four_ac
root_part = sp.sqrt(discriminant_value)
root1 = (-b_val + root_part) / (2 * a_val)
root2 = (-b_val - root_part) / (2 * a_val)

# 素因数分解
discriminant_factors = sp.factorint(discriminant_value)

# 結果表示
print(f"解の公式: (-b ± √(b^2 - 4ac)) / 2a")
print(f"a = {a_val}, b = {b_val}, c = {c_val}")
print(f"b^2 = {b_squared}")
print(f"4ac = {four_ac}")
print(f"判別式 (b^2 - 4ac) = {discriminant_value}")
print(f"2a(b / (2a)) = {2*a_val*(b_val / (2*a_val))}")
print(f"√(b^2 - 4ac) = {root_part}")
print(f"(√(b^2 - 4ac)) / (2a) = {root_part / (2*a_val)}")
print(f"解1: {root1}")
print(f"解2: {root2}")

# 判別式の素因数分解
print(f"判別式の素因数分解: {discriminant_factors}")

import sympy as sp

# 変数定義
a = 3
b = 1
c = 9

# 判別式の計算
b2 = b**2
ac4 = 4 * a * c
D = b2 - ac4  # 判別式 Δ = b^2 - 4ac

# 二次方程式の解の公式
x1 = (-b + sp.sqrt(D)) / (2 * a)
x2 = (-b - sp.sqrt(D)) / (2 * a)

# 2a(b / (2a)) の計算
term_2a = 2 * a * (b / (2 * a))

# √(b^2 - 4ac) の計算
sqrt_D = sp.sqrt(D)

# (√(b^2 - 4ac)) / (2a) の計算
sqrt_D_2a = sqrt_D / (2 * a)

# 勾配法とニュートン法で数値解を求める
def gradient_descent(f, x0, alpha=0.01, tol=1e-6, max_iter=1000):
    x = x0
    f_prime = sp.diff(f, x_var)
    for _ in range(max_iter):
        grad = f_prime.subs(x_var, x)
        if abs(grad) < tol:
            break
        x = x - alpha * grad
    return x

def newton_method(f, x0, tol=1e-6, max_iter=100):
    x = x0
    f_prime = sp.diff(f, x_var)
    f_double_prime = sp.diff(f_prime, x_var)
    for _ in range(max_iter):
        f_val = f.subs(x_var, x)
        f_prime_val = f_prime.subs(x_var, x)
        if abs(f_prime_val) < tol:
            break
        x = x - f_val / f_prime_val
    return x

# 二次方程式の定義
x_var = sp.Symbol('x')
quadratic_eq = a * x_var**2 + b * x_var + c

# 勾配法とニュートン法で数値解を求める
gd_solution = gradient_descent(quadratic_eq, x0=0)
newton_solution = newton_method(quadratic_eq, x0=0)

# 指定された数値の約数を求める関数
def get_divisors(n):
    n = int(abs(n))  # 整数に変換
    return [i for i in range(1, n + 1) if n % i == 0]

# 各値の約数を求める
divisors_dict = {
    "a": get_divisors(a),
    "b": get_divisors(b),
    "c": get_divisors(c),
    "b^2": get_divisors(b2),
    "4ac": get_divisors(ac4),
    "b^2 - 4ac": get_divisors(D),
    "2a(b/(2a))": get_divisors(term_2a),
    "√(b^2-4ac)": get_divisors(int(sqrt_D) if sqrt_D.is_real else 0),
    "(√(b^2-4ac))/(2a)": get_divisors(int(sqrt_D_2a) if sqrt_D_2a.is_real else 0),
}

# 結果を出力
print("=== Quadratic Equation Solution ===")
print(f"x1 = {x1}, x2 = {x2}")

print("\n=== Gradient Descent Solution ===")
print(f"Approximate Root: {gd_solution}")

print("\n=== Newton's Method Solution ===")
print(f"Approximate Root: {newton_solution}")

print("\n=== Divisors of Key Values ===")
for key, divisors in divisors_dict.items():
    print(f"{key}: {divisors}")

お客様に提供する「二次関数のグラフ25」ソリューション

# ==============================================
# 二次関数の最小値(解析・勾配法・ベイズ最適化)
# f(x) = Ax² + Bx + C,  A=4, B=1, C=8
# ==============================================

import numpy as np
import matplotlib.pyplot as plt

# ------------------------------
# パラメータの定義 / Define parameters
# ------------------------------
A = 4
B = 1
C = 8

# ------------------------------
# 関数定義 / Define the function
# ------------------------------
def f(x):
    return A * x**2 + B * x + C

# ------------------------------
# 解析解 / Completing the Square
# ------------------------------
vertex_x = -B / (2 * A)
vertex_y = f(vertex_x)

# ------------------------------
# 勾配法(最急降下法) / Gradient Descent
# ------------------------------
def grad_f(x):
    return 2 * A * x + B  # f'(x)

x_gd = 2.0  # 初期値
alpha = 0.1  # 学習率
for _ in range(30):
    x_gd -= alpha * grad_f(x_gd)

gd_y = f(x_gd)

# ------------------------------
# ベイズ最適化 / Bayesian Optimization
# ------------------------------
!pip install -q scikit-optimize
from skopt import gp_minimize
from skopt.space import Real

res = gp_minimize(lambda x: f(x[0]), dimensions=[Real(-5, 5)], n_calls=30)
x_bayes = res.x[0]
y_bayes = f(x_bayes)

# ------------------------------
# 結果表示 / Print Results
# ------------------------------
print("【最小値の比較 / Minimum Value Comparison】\n")

print(" 解析解 / Analytical Solution")
print(f"最小点 x = {vertex_x:.5f}")
print(f"最小値 f(x) = {vertex_y:.5f}\n")

print(" 勾配法 / Gradient Descent")
print(f"最小点 x = {x_gd:.5f}")
print(f"最小値 f(x) = {gd_y:.5f}\n")

print(" ベイズ最適化 / Bayesian Optimization")
print(f"最小点 x = {x_bayes:.5f}")
print(f"最小値 f(x) = {y_bayes:.5f}\n")

# ------------------------------
# グラフ描画 / Plotting
# ------------------------------
x_vals = np.linspace(-2, 2, 400)
y_vals = f(x_vals)

plt.figure(figsize=(10, 6))
plt.plot(x_vals, y_vals, label=f'f(x) = {A}x² + {B}x + {C}', color='black')

# 解析解
plt.scatter(vertex_x, vertex_y, color='red', label='Vertex (Analytical)', zorder=5)

# 勾配法
plt.scatter(x_gd, gd_y, color='blue', label='Gradient Descent', zorder=5)

# ベイズ最適化
plt.scatter(x_bayes, y_bayes, color='green', label='Bayesian Optimization', zorder=5)

plt.title("Minimum of a Quadratic Function by Three Methods")
plt.xlabel("x")
plt.ylabel("f(x)")
plt.grid(True)
plt.legend()
plt.show()


お客様に提供する「複素数31」ソリューション

import numpy as np
import matplotlib.pyplot as plt

# -----------------------------
# 複素数の定義
# -----------------------------
z1 = complex(3, 1)    # 3 + i
z2 = complex(2, -4)   # 2 - 4i

# 掛け算
z_product = z1 * z2

# -----------------------------
# 計算結果の出力
# -----------------------------
print("【複素数の掛け算】")
print(f"z₁ = {z1.real} + {z1.imag}i")
print(f"z₂ = {z2.real} + {z2.imag}i")
print(f"z₁ × z₂ = {z_product.real:.2f} + {z_product.imag:.2f}i")

# -----------------------------
# 複素平面にプロット
# -----------------------------
plt.figure(figsize=(6, 6))
plt.axhline(0, color='gray', linestyle='--')
plt.axvline(0, color='gray', linestyle='--')

# z1
plt.quiver(0, 0, z1.real, z1.imag, angles='xy', scale_units='xy', scale=1, color='blue', label='z₁ = 3 + i')

# z2
plt.quiver(0, 0, z2.real, z2.imag, angles='xy', scale_units='xy', scale=1, color='green', label='z₂ = 2 - 4i')

# z1 × z2
plt.quiver(0, 0, z_product.real, z_product.imag, angles='xy', scale_units='xy', scale=1, color='red', label='z₁ × z₂')

plt.xlim(-20, 10)
plt.ylim(-20, 10)
plt.gca().set_aspect('equal', adjustable='box')
plt.grid(True)
plt.title("Multiplication of Complex Numbers")
plt.xlabel("Re")
plt.ylabel("Im")
plt.legend()
plt.show()

お客様に提供する「高次方程式34」ソリューション

# ===============================================
# f(x) = x^3 + Ax^2 + Bx + C の因数分解とプロット
# A=3, B=-2, C=-2
# ===============================================

import numpy as np
import matplotlib.pyplot as plt
import sympy as sp

# ------------------------------
# 定義 / Define symbols and function
# ------------------------------
x = sp.Symbol('x')
A, B, C = 3, -2, -2

f_expr = x**3 + A * x**2 + B * x + C
f_factored = sp.factor(f_expr)

print("【多項式の式 / Original Polynomial】")
print(f"f(x) = {f_expr}\n")

print("【因数分解結果 / Factored Form】")
print(f"f(x) = {f_factored}\n")

# ------------------------------
# 数値用関数に変換 / Convert to numerical function
# ------------------------------
f_lambdified = sp.lambdify(x, f_expr, modules=['numpy'])

# ------------------------------
# プロット / Plot the function
# ------------------------------
x_vals = np.linspace(-5, 3, 400)
y_vals = f_lambdified(x_vals)

plt.figure(figsize=(10, 6))
plt.plot(x_vals, y_vals, label=f'$f(x) = x^3 + {A}x^2 + ({B})x + ({C})$')
plt.axhline(0, color='gray', linestyle='--', linewidth=1)
plt.axvline(0, color='gray', linestyle='--', linewidth=1)
plt.title("Cubic Function and Its Roots")
plt.xlabel("x")
plt.ylabel("f(x)")
plt.grid(True)
plt.legend()
plt.show()

お客様に提供する「解と係数の関係35」ソリューション

# ========================================
# 解と係数の関係 / Relationship between roots and coefficients
# 2次方程式: ax² + bx + c = 0
# ========================================

import math

# -----------------------------
# 係数の設定 / Set coefficients
# -----------------------------
a = 1
b = -5
c = 6

# -----------------------------
# 解の計算 / Calculate roots
# -----------------------------
# 判別式 / Discriminant
D = b**2 - 4*a*c

if D >= 0:
    # 実数解 / Real roots
    root1 = (-b + math.sqrt(D)) / (2*a)
    root2 = (-b - math.sqrt(D)) / (2*a)

    # -----------------------------
    # 解と係数の関係の確認 / Check relationship
    # -----------------------------
    sum_roots = root1 + root2
    product_roots = root1 * root2

    print("【2次方程式: ax² + bx + c = 0】")
    print(f"与えられた係数 / Coefficients: a={a}, b={b}, c={c}\n")
    
    print("▶ 実数解 / Real Roots:")
    print(f"  x₁ = {root1:.2f}, x₂ = {root2:.2f}\n")

    print("▶ 解と係数の関係 / Relationship:")
    print(f"  x₁ + x₂ = {-b/a:.2f} ←→ -b/a = {sum_roots:.2f}")
    print(f"  x₁ × x₂ = {c/a:.2f} ←→  c/a = {product_roots:.2f}")
else:
    print("実数解が存在しません(判別式 < 0)")

お客様に提供する「連立方程式37」ソリューション

import numpy as np
import matplotlib.pyplot as plt

# 連立方程式:
# 2x + y = 8
# 3x - y = 1

# ------------------------------------------------
# 1. クラメルの公式 / Cramer's Rule
# ------------------------------------------------
# 係数行列
A = np.array([[2, 1],
              [3, -1]])
# 定数ベクトル
B = np.array([8, 1])

# 行列式(determinant)
D = np.linalg.det(A)

# Dx: 定数列とx列を入れ替えた行列の行列式
Dx = np.linalg.det(np.array([[8, 1],
                             [1, -1]]))

# Dy: 定数列とy列を入れ替えた行列の行列式
Dy = np.linalg.det(np.array([[2, 8],
                             [3, 1]]))

# 解
x_cramer = Dx / D
y_cramer = Dy / D

print("【クラメルの公式 / Cramer's Rule】")
print(f"x = {x_cramer:.2f}, y = {y_cramer:.2f}\n")

# ------------------------------------------------
# 2. NumPyの解法 / Using NumPy linear solver
# ------------------------------------------------
solution_np = np.linalg.solve(A, B)
x_np, y_np = solution_np

print("【NumPy解法 / NumPy Solver】")
print(f"x = {x_np:.2f}, y = {y_np:.2f}\n")

# ------------------------------------------------
# 3. 加減法 / Elimination Method (手計算風)
# ------------------------------------------------
# 式1: 2x + y = 8
# 式2: 3x - y = 1

# 式1と式2を加算(yを消去)
# 2x + y + 3x - y = 8 + 1 → 5x = 9 → x = 9/5
x_elim = 9 / 5

# xを式1に代入して y を求める
# 2*(9/5) + y = 8 → y = 8 - 18/5 = 22/5
y_elim = 22 / 5

print("【加減法 / Elimination Method】")
print(f"x = {x_elim:.2f}, y = {y_elim:.2f}\n")

# ------------------------------------------------
# グラフ描画 / Plotting the two lines
# ------------------------------------------------
x_vals = np.linspace(0, 5, 100)
y1_vals = 8 - 2 * x_vals  # y = -2x + 8
y2_vals = 3 * x_vals - 1  # y = 3x - 1

plt.figure(figsize=(8, 6))
plt.plot(x_vals, y1_vals, label="2x + y = 8")
plt.plot(x_vals, y2_vals, label="3x - y = 1")

# 解をマーカーで表示
plt.scatter(x_cramer, y_cramer, color='red', label="Solution", zorder=5)

plt.title("Solution of Linear Equations")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)
plt.legend()
plt.axhline(0, color='gray', linewidth=0.5)
plt.axvline(0, color='gray', linewidth=0.5)
plt.show()

お客様に提供する「いろいろな方程式36」ソリューション

import numpy as np
import matplotlib.pyplot as plt

# ------------------------------
# パラメータ A の設定
# ------------------------------
A = 2

# ------------------------------
# 関数定義 / Define functions
# ------------------------------
def f1(x):  # f1(x) = |x - A|
    return np.abs(x - A)

def f2(x):  # f2(x) = A - x²
    return A - x**2

# ------------------------------
# プロット範囲 / Plot range
# ------------------------------
x_vals = np.linspace(A - 5, A + 5, 400)
y1_vals = f1(x_vals)
y2_vals = f2(x_vals)

# ------------------------------
# グラフ描画 / Plotting
# ------------------------------
plt.figure(figsize=(10, 6))

plt.plot(x_vals, y1_vals, label=r'$f_1(x) = |x - A|$', color='blue')
plt.plot(x_vals, y2_vals, label=r'$f_2(x) = A - x^2$', color='orange')

# A点の表示
plt.axvline(x=A, color='gray', linestyle='--', linewidth=1)
plt.text(A + 0.1, max(max(y1_vals), max(y2_vals)) * 0.9, f"A = {A}", color='gray')

plt.title("Graphs of $|x - A|$ and $A - x^2$")
plt.xlabel("x")
plt.ylabel("f(x)")
plt.grid(True)
plt.legend()
plt.show()

お客様に提供する「角の表し方43」ソリューション

import math

# -------------------------------
# 度 → ラジアン(degrees → radians)
# -------------------------------
def degrees_to_radians(deg):
    return math.radians(deg)  # または deg * math.pi / 180

# -------------------------------
# ラジアン → 度(radians → degrees)
# -------------------------------
def radians_to_degrees(rad):
    return math.degrees(rad)  # または rad * 180 / math.pi

# -------------------------------
# 変換の例 / Examples
# -------------------------------
deg = 180
rad = degrees_to_radians(deg)
print(f"{deg}° = {rad:.4f} rad")

rad_input = math.pi / 2
deg_converted = radians_to_degrees(rad_input)
print(f"{rad_input:.4f} rad = {deg_converted:.2f}°")

お客様に提供する「有名角44」ソリューション

import math
from fractions import Fraction

# -------------------------------
# 有名角リスト(度) / Famous angles in degrees
# -------------------------------
angles_deg = [0, 30, 45, 60, 90]

# -------------------------------
# 計算&表示
# -------------------------------
print("【有名角の三角関数と逆三角関数 / Famous Angles and Trig Functions】\n")

for deg in angles_deg:
    rad = math.radians(deg)  # ラジアンに変換
    sin_val = math.sin(rad)
    cos_val = math.cos(rad)
    try:
        tan_val = math.tan(rad)
    except:
        tan_val = float('inf')

    print(f"角度: {deg}° / {rad:.4f} rad")
    print(f"  sin({deg}) = {Fraction(sin_val).limit_denominator(100)}{sin_val:.4f}")
    print(f"  cos({deg}) = {Fraction(cos_val).limit_denominator(100)}{cos_val:.4f}")
    if deg != 90:
        print(f"  tan({deg}) = {Fraction(tan_val).limit_denominator(100)}{tan_val:.4f}")
    else:
        print(f"  tan({deg}) = ∞(定義されない)")
    
    # 逆三角関数(ラジアン)→ 度に変換
    if deg != 90:
        arc_sin_deg = math.degrees(math.asin(sin_val))
        arc_cos_deg = math.degrees(math.acos(cos_val))
        arc_tan_deg = math.degrees(math.atan(tan_val)) if deg != 90 else None
        print(f"  arcsin(sin({deg})) ≈ {arc_sin_deg:.1f}°")
        print(f"  arccos(cos({deg})) ≈ {arc_cos_deg:.1f}°")
        print(f"  arctan(tan({deg})) ≈ {arc_tan_deg:.1f}°")
    print("-" * 50)

お客様に提供する「相互関係47」ソリューション

import numpy as np
import matplotlib.pyplot as plt

# --------------------------
# θの定義(度→ラジアン) / Define θ in radians
# --------------------------
theta_deg = np.linspace(0, 360, 1000)
theta_rad = np.radians(theta_deg)

# --------------------------
# 各関数の計算 / Compute trig functions
# --------------------------
sin_vals = np.sin(theta_rad)
cos_vals = np.cos(theta_rad)
tan_vals = np.tan(theta_rad)

# 1. sin²θ + cos²θ
identity1 = sin_vals**2 + cos_vals**2

# 2. tanθ = sinθ / cosθ (cosθ≠0の部分のみ計算)
tan_defined = cos_vals != 0
tan_ratio = np.full_like(theta_rad, np.nan)
tan_ratio[tan_defined] = sin_vals[tan_defined] / cos_vals[tan_defined]

# 3. tan²θ + 1 = 1 / cos²θ
tan_sq_plus1 = np.full_like(theta_rad, np.nan)
rhs_identity3 = np.full_like(theta_rad, np.nan)
tan_sq_plus1[tan_defined] = (tan_vals[tan_defined])**2 + 1
rhs_identity3[tan_defined] = 1 / (cos_vals[tan_defined])**2

# --------------------------
# グラフ描画 / Plotting
# --------------------------
plt.figure(figsize=(12, 8))

# 1. sin²θ + cos²θ = 1
plt.subplot(3, 1, 1)
plt.plot(theta_deg, identity1, label=r'$\sin^2\theta + \cos^2\theta$', color='purple')
plt.axhline(1, color='gray', linestyle='--', linewidth=1, label='= 1')
plt.title("Identity 1: sin²θ + cos²θ = 1")
plt.ylim(0.9, 1.1)
plt.xlabel("θ (degrees)")
plt.ylabel("Value")
plt.legend()
plt.grid(True)

# 2. tanθ = sinθ / cosθ
plt.subplot(3, 1, 2)
plt.plot(theta_deg, tan_vals, label='tan(θ)', color='orange', linestyle='--')
plt.plot(theta_deg, tan_ratio, label='sin(θ)/cos(θ)', color='blue')
plt.title("Identity 2: tanθ = sinθ / cosθ")
plt.ylim(-10, 10)
plt.xlabel("θ (degrees)")
plt.ylabel("Value")
plt.legend()
plt.grid(True)

# 3. tan²θ + 1 = 1 / cos²θ
plt.subplot(3, 1, 3)
plt.plot(theta_deg, tan_sq_plus1, label=r'$\tan^2\theta + 1$', color='green')
plt.plot(theta_deg, rhs_identity3, label=r'$1 / \cos^2\theta$', color='red', linestyle='--')
plt.title("Identity 3: tan²θ + 1 = 1 / cos²θ")
plt.ylim(0, 20)
plt.xlabel("θ (degrees)")
plt.ylabel("Value")
plt.legend()
plt.grid(True)

plt.tight_layout()
plt.show()

お客様に提供する「加法定理48」ソリューション

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# ------------------------------
# a, b を -π ~ π の範囲で生成
# ------------------------------
a = np.linspace(-np.pi, np.pi, 100)
b = np.linspace(-np.pi, np.pi, 100)
A, B = np.meshgrid(a, b)

# ------------------------------
# 左辺:sin(a + b)
# ------------------------------
lhs = np.sin(A + B)

# ------------------------------
# 右辺:sin(a)cos(b) + cos(a)sin(b)
# ------------------------------
rhs = np.sin(A) * np.cos(B) + np.cos(A) * np.sin(B)

# ------------------------------
# 差の絶対値(誤差確認用)
# ------------------------------
diff = np.abs(lhs - rhs)

# ------------------------------
# 3Dプロット / Plot both sides
# ------------------------------
fig = plt.figure(figsize=(18, 6))

# --- 左辺 ---
ax1 = fig.add_subplot(1, 3, 1, projection='3d')
ax1.plot_surface(A, B, lhs, cmap='viridis')
ax1.set_title('LHS: sin(a + b)')
ax1.set_xlabel('a')
ax1.set_ylabel('b')
ax1.set_zlabel('Value')

# --- 右辺 ---
ax2 = fig.add_subplot(1, 3, 2, projection='3d')
ax2.plot_surface(A, B, rhs, cmap='plasma')
ax2.set_title('RHS: sin(a)cos(b) + cos(a)sin(b)')
ax2.set_xlabel('a')
ax2.set_ylabel('b')
ax2.set_zlabel('Value')

# --- 差分確認 ---
ax3 = fig.add_subplot(1, 3, 3, projection='3d')
ax3.plot_surface(A, B, diff, cmap='inferno')
ax3.set_title('Difference |LHS - RHS|')
ax3.set_xlabel('a')
ax3.set_ylabel('b')
ax3.set_zlabel('Error')

plt.tight_layout()
plt.show()

お客様に提供する「2倍角の公式半角の公式49」ソリューション


import numpy as np
import matplotlib.pyplot as plt

# 角度(ラジアン)の設定
theta = np.linspace(0, 2 * np.pi, 400)

# 2倍角の公式
sin2θ = 2 * np.sin(theta) * np.cos(theta)
cos2θ_sin = 1 - 2 * np.sin(theta)**2
cos2θ_cos = 2 * np.cos(theta)**2 - 1
tanθ = np.tan(theta)
tan2θ = 2 * tanθ / (1 - tanθ**2)
tan2θ[np.abs(1 - tanθ**2) < 0.01] = np.nan  # 発散箇所の除外

# 半角の公式(theta/2)
theta_half = theta / 2
sin2_half = (1 - np.cos(theta)) / 2
cos2_half = (1 + np.cos(theta)) / 2
tan2_half = (1 - np.cos(theta)) / (1 + np.cos(theta))

# プロット
fig, axs = plt.subplots(3, 2, figsize=(14, 12))
axs = axs.ravel()

axs[0].plot(theta, sin2θ, label=r'$\sin(2\theta)$')
axs[0].set_title('sin(2θ) = 2sinθcosθ')
axs[0].grid(True)
axs[0].legend()

axs[1].plot(theta, cos2θ_sin, label=r'$\cos(2\theta) = 1 - 2\sin^2\theta$')
axs[1].plot(theta, cos2θ_cos, '--', label=r'$\cos(2\theta) = 2\cos^2\theta - 1$')
axs[1].set_title('cos(2θ) (sin and cos forms)')
axs[1].grid(True)
axs[1].legend()

axs[2].plot(theta, tan2θ, label=r'$\tan(2\theta) = \frac{2\tan\theta}{1 - \tan^2\theta}$')
axs[2].set_ylim(-10, 10)
axs[2].set_title('tan(2θ) = 2tanθ / (1 - tan²θ)')
axs[2].grid(True)
axs[2].legend()

axs[3].plot(theta, sin2_half, label=r'$\sin^2(\theta/2) = \frac{1 - \cos\theta}{2}$')
axs[3].set_title('sin²(θ/2)')
axs[3].grid(True)
axs[3].legend()

axs[4].plot(theta, cos2_half, label=r'$\cos^2(\theta/2) = \frac{1 + \cos\theta}{2}$')
axs[4].set_title('cos²(θ/2)')
axs[4].grid(True)
axs[4].legend()

axs[5].plot(theta, tan2_half, label=r'$\tan^2(\theta/2) = \frac{1 - \cos\theta}{1 + \cos\theta}$')
axs[5].set_ylim(0, 10)
axs[5].set_title('tan²(θ/2)')
axs[5].grid(True)
axs[5].legend()

plt.tight_layout()
plt.show()

お客様に提供する「合成50」ソリューション


import numpy as np
import matplotlib.pyplot as plt
from fractions import Fraction

# 定義する変数 a と b
a = 3
b = 4

# 合成公式に基づくαとβの計算
alpha = np.arctan2(b, a)  # tanα = b/a から計算
beta = np.arctan2(a, b)   # tanβ = a/b から計算

# αとβを分数と小数で表示
alpha_frac = Fraction(np.tan(alpha)).limit_denominator(1000)
beta_frac = Fraction(np.tan(beta)).limit_denominator(1000)

# ラジアンを度数に変換
alpha_deg = np.degrees(alpha)
beta_deg = np.degrees(beta)

# θ の範囲を設定
theta = np.linspace(0, 2 * np.pi, 400)

# a sinθ + b cosθ の計算
lhs = a * np.sin(theta) + b * np.cos(theta)

# 合成した三角関数(sinθ + α の形式)
rhs_sin = np.sqrt(a**2 + b**2) * np.sin(theta + alpha)

# 合成した三角関数(cosθ - β の形式)
rhs_cos = np.sqrt(a**2 + b**2) * np.cos(theta - beta)

# プロット
plt.figure(figsize=(10, 6))

# 左辺のグラフ
plt.plot(theta, lhs, label="a sin(θ) + b cos(θ)", linestyle='--')

# 右辺の sin 合成
plt.plot(theta, rhs_sin, label="√(a² + b²) sin(θ + α)", linestyle='-.')

# 右辺の cos 合成
plt.plot(theta, rhs_cos, label="√(a² + b²) cos(θ - β)", linestyle=':')

# ラベル付けとタイトル
plt.xlabel('θ (radians)')
plt.ylabel('Value')
plt.title('Trigonometric Function Synthesis')
plt.legend()

# プロット表示
plt.grid(True)
plt.show()

# αとβの値をプリント(分数、小数、度数)
print(f"α (radians): {alpha} ({alpha_frac}) = {alpha_deg}°")
print(f"β (radians): {beta} ({beta_frac}) = {beta_deg}°")

お客様に提供する「和積の公式51」ソリューション

import numpy as np
import matplotlib.pyplot as plt

# 角度(ラジアン)の設定
alpha = np.linspace(0, 2 * np.pi, 400)
beta = np.linspace(0, 2 * np.pi, 400)

# 積和の公式
lhs_sin_cos = np.sin(alpha) * np.cos(beta)  # sinα * cosβ
rhs_sin_cos = (np.sin(alpha + beta) + np.sin(alpha - beta)) / 2  # (sin(α+β) + sin(α-β)) / 2

lhs_cos_sin = np.cos(alpha) * np.sin(beta)  # cosα * sinβ
rhs_cos_sin = (np.sin(alpha + beta) - np.sin(alpha - beta)) / 2  # (sin(α+β) - sin(α-β)) / 2

lhs_cos_cos = np.cos(alpha) * np.cos(beta)  # cosα * cosβ
rhs_cos_cos = (np.cos(alpha + beta) + np.cos(alpha - beta)) / 2  # (cos(α+β) + cos(α-β)) / 2

lhs_sin_sin = np.sin(alpha) * np.sin(beta)  # sinα * sinβ
rhs_sin_sin = -(np.cos(alpha + beta) - np.cos(alpha - beta)) / 2  # -(cos(α+β) - cos(α-β)) / 2

# 和積の公式
A = alpha + beta
B = alpha - beta

rhs_sin_sum = 2 * np.sin((A + B) / 2) * np.cos((A - B) / 2)  # sinA + sinB
rhs_cos_sum = 2 * np.cos((A + B) / 2) * np.cos((A - B) / 2)  # cosA + cosB
rhs_sin_diff = 2 * np.cos((A + B) / 2) * np.sin((A - B) / 2)  # sinA - sinB
rhs_cos_diff = -2 * np.sin((A + B) / 2) * np.sin((A - B) / 2)  # cosA - cosB

# プロット
plt.figure(figsize=(12, 8))

# 積和の公式のプロット
plt.subplot(2, 2, 1)
plt.plot(alpha, lhs_sin_cos, label="sinα * cosβ")
plt.plot(alpha, rhs_sin_cos, label="(sin(α+β) + sin(α-β))/2", linestyle='--')
plt.title("sinα * cosβ vs (sin(α+β) + sin(α-β))/2")
plt.legend()

plt.subplot(2, 2, 2)
plt.plot(alpha, lhs_cos_sin, label="cosα * sinβ")
plt.plot(alpha, rhs_cos_sin, label="(sin(α+β) - sin(α-β))/2", linestyle='--')
plt.title("cosα * sinβ vs (sin(α+β) - sin(α-β))/2")
plt.legend()

plt.subplot(2, 2, 3)
plt.plot(alpha, lhs_cos_cos, label="cosα * cosβ")
plt.plot(alpha, rhs_cos_cos, label="(cos(α+β) + cos(α-β))/2", linestyle='--')
plt.title("cosα * cosβ vs (cos(α+β) + cos(α-β))/2")
plt.legend()

plt.subplot(2, 2, 4)
plt.plot(alpha, lhs_sin_sin, label="sinα * sinβ")
plt.plot(alpha, rhs_sin_sin, label="-(cos(α+β) - cos(α-β))/2", linestyle='--')
plt.title("sinα * sinβ vs -(cos(α+β) - cos(α-β))/2")
plt.legend()

plt.tight_layout()
plt.show()



お客様に提供する「三平方の定理52」ソリューション


import sympy as sp

# AとBの値を定義
A = 10
B = 3

# 各項の計算
A_squared = A**2
B_squared = B**2
A_plus_B = A + B
A_minus_B = A - B
A_squared_plus_B_squared = A_squared + B_squared  # A^2 + B^2

# 三平方の定理に基づく斜辺(c)を計算
c = sp.sqrt(A_squared + B_squared)

# (A + B) × (A - B)の計算
A_plus_B_times_A_minus_B = (A + B) * (A - B)

# 因数を求める(因数分解ではなく因数をリスト)
factors_A_squared = sp.factorint(A_squared)
factors_B_squared = sp.factorint(B_squared)
factors_A_plus_B = sp.factorint(A_plus_B)
factors_A_minus_B = sp.factorint(A_minus_B)
factors_A_squared_plus_B_squared = sp.factorint(A_squared_plus_B_squared)
factors_A_plus_B_times_A_minus_B = sp.factorint(A_plus_B_times_A_minus_B)

# 結果を表示
print(f"A = {A}")
print(f"B = {B}")
print(f"A^2 = {A_squared}")
print(f"B^2 = {B_squared}")
print(f"A^2 + B^2 = {A_squared_plus_B_squared}")
print(f"斜辺 (c) = {c}")

print(f"(A + B) × (A - B) = {A_plus_B_times_A_minus_B}")

print(f"\n因数:")
print(f"A^2 の因数: {factors_A_squared}")
print(f"B^2 の因数: {factors_B_squared}")
print(f"A + B の因数: {factors_A_plus_B}")
print(f"A - B の因数: {factors_A_minus_B}")
print(f"A^2 + B^2 の因数: {factors_A_squared_plus_B_squared}")
print(f"(A + B) × (A - B) の因数: {factors_A_plus_B_times_A_minus_B}")


お客様に提供する「相似55」ソリューション

import numpy as np
import matplotlib.pyplot as plt

# A と B の定義
A = 3
B = 2

# 定数 K の計算
K = B / A

# 入力の範囲を設定(例:0から10まで)
input_values = np.linspace(0, 10, 100)

# 出力の計算
output_values = K * input_values

# 入力が2のときの出力をプリント
input_value_at_2 = 2
output_at_2 = K * input_value_at_2
print(f"入力が {input_value_at_2} のときの出力: {output_at_2}")

# プロット
plt.figure(figsize=(8, 6))
plt.plot(input_values, output_values, label=fr'$Output = \dfrac{{{B}}}{{{A}}} \times Input$', color='blue')
plt.scatter(input_value_at_2, output_at_2, color='red', zorder=5, label=f'Output at Input = {input_value_at_2}')

# ラベルとタイトル設定(Kの分数も表示)
plt.xlabel('Input')
plt.ylabel('Output')
plt.title(fr'Output = K × Input   where   $K = \dfrac{{{B}}}{{{A}}} = {K:.2f}$')
plt.legend()
plt.grid(True)

# プロット表示
plt.show()

お客様に提供する「正弦定理と余弦定理」ソリューション

import numpy as np
import matplotlib.pyplot as plt

# ==== 三角形の既知の情報 / Given triangle data ====
# 辺 a, b と 角C(degree)
a = 5   # side a
b = 7   # side b
C_deg = 60  # angle C in degrees

# ==== ラジアンに変換 / Convert to radians ====
C_rad = np.radians(C_deg)

# ==== 余弦定理から辺cを計算 / Use Cosine Law to calculate side c ====
# c^2 = a^2 + b^2 - 2ab*cos(C)
c = np.sqrt(a**2 + b**2 - 2*a*b*np.cos(C_rad))

# ==== 正弦定理から角A, Bを計算 / Use Sine Law to calculate angles A and B ====
# sin(A)/a = sin(C)/c
A_rad = np.arcsin(np.sin(C_rad) * a / c)
B_rad = np.pi - C_rad - A_rad  # 三角形の内角の和は180度

# ==== 角度に変換 / Convert to degrees ====
A_deg = np.degrees(A_rad)
B_deg = np.degrees(B_rad)

# ==== 結果表示 / Print results ====
print("=== Triangle Calculation ===")
print(f"Side c = {c:.2f}")
print(f"Angle A = {A_deg:.2f} degrees")
print(f"Angle B = {B_deg:.2f} degrees")

# ==== プロット(スケーリング用)/ Triangle plotting ====
# 頂点Aを原点に、Bをx軸上に、Cを計算して配置
A_point = np.array([0, 0])
B_point = np.array([c, 0])
# C点の座標を計算
Cx = b * np.cos(A_rad)
Cy = b * np.sin(A_rad)
C_point = np.array([Cx, Cy])

# ==== 三角形プロット / Plot the triangle ====
plt.figure(figsize=(6, 6))
plt.plot([A_point[0], B_point[0]], [A_point[1], B_point[1]], label='Side c')
plt.plot([B_point[0], C_point[0]], [B_point[1], C_point[1]], label='Side a')
plt.plot([C_point[0], A_point[0]], [C_point[1], A_point[1]], label='Side b')

# 点のラベル / Mark vertices
for point, label in zip([A_point, B_point, C_point], ['A', 'B', 'C']):
    plt.scatter(*point)
    plt.text(point[0], point[1], f' {label}', fontsize=12)

plt.title("Triangle using Sine and Cosine Rules")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.axis('equal')
plt.grid(True)
plt.legend()
plt.show()

# ==== アンテナの工学的設定 / Engineering Setup ====
# 高さ(vertical difference)と水平距離
h = 15     # height difference [m]
d = 40     # horizontal distance [m]

# ==== 総距離(斜辺)/ Total distance ====
L = np.sqrt(h**2 + d**2)

# ==== 仰角の計算(atan使用)/ Elevation angle ====
angle_rad = np.arctan(h / d)
angle_deg = np.degrees(angle_rad)

print("\n=== Engineering Application (Antenna Angle) ===")
print(f"Total distance = {L:.2f} m")
print(f"Elevation angle = {angle_deg:.2f} degrees")

# ==== プロット(アンテナ角度)/ Antenna diagram ====
plt.figure(figsize=(6, 5))
plt.plot([0, d], [0, h], label='Line of Sight (L)')
plt.plot([0, d], [0, 0], 'k--', label='Ground')
plt.plot([d, d], [0, h], 'k:', label='Height')

# 注釈 / Annotate
plt.text(d/2, h/2, f'{angle_deg:.1f}°', fontsize=12, color='blue')
plt.text(d + 1, h/2, f'h = {h} m', fontsize=10)
plt.text(d/2, -2, f'd = {d} m', fontsize=10)

plt.xlabel("Distance [m]")
plt.ylabel("Height [m]")
plt.title("Antenna Tilt Angle Calculation")
plt.axis('equal')
plt.grid(True)
plt.legend()
plt.show()

お客様に提供する「内積65」ソリューション


import numpy as np

# ベクトルの定義
a = np.array([3, 2])
b = np.array([1, 4])

# 内積の計算
dot = np.dot(a, b)

# ノルム(大きさ)
norm_a = np.linalg.norm(a)
norm_b = np.linalg.norm(b)

# 角度(cosθ → θ に変換)
cos_theta = dot / (norm_a * norm_b)
theta_rad = np.arccos(cos_theta)
theta_deg = np.degrees(theta_rad)

# 結果表示
print("【内積の計算結果】")
print(f"a = {a}")
print(f"b = {b}")
print(f"a ・ b = {dot}")
print(f"|a| = {norm_a:.4f}, |b| = {norm_b:.4f}")
print(f"cosθ = {cos_theta:.4f}")
print(f"∠θ = {theta_deg:.2f}°")


お客様に提供する「正射影ベクトル67」ソリューション

import numpy as np
import matplotlib.pyplot as plt

# ------------------------------
# 点 P(x, y) と ベクトル A(a, b) を定義 / Define point and direction vector
# ------------------------------
x, y = 2, 3         # 点 P の座標 / Point P
a, b = 1, 2         # ベクトルAの成分

# ベクトル OP / Vector OP
OP = np.array([x, y])

# ベクトル A / Direction vector A
A = np.array([a, b])

# ------------------------------
# 正射影ベクトル OH を計算 / Compute projection vector OH
# ------------------------------
dot_product = np.dot(OP, A)              # 内積 / Dot product
norm_squared = np.dot(A, A)              # ベクトルAの大きさの2乗 / |A|^2
projection_scalar = dot_product / norm_squared
OH = projection_scalar * A               # 正射影ベクトル OH

# ------------------------------
# プロット設定 / Plotting
# ------------------------------
plt.figure(figsize=(8, 8))
plt.axhline(0, color='gray', linewidth=0.5)
plt.axvline(0, color='gray', linewidth=0.5)

# 原点からのベクトルを描画
plt.quiver(0, 0, x, y, angles='xy', scale_units='xy', scale=1, color='blue', label='OP (P=({}, {}))'.format(x, y))
plt.quiver(0, 0, a, b, angles='xy', scale_units='xy', scale=1, color='green', alpha=0.4, label='Vector A')
plt.quiver(0, 0, OH[0], OH[1], angles='xy', scale_units='xy', scale=1, color='red', label='Projection OH')

# 点とラベルの追加
plt.plot(x, y, 'bo')
plt.text(x + 0.2, y, 'P({},{})'.format(x, y), color='blue')
plt.plot(OH[0], OH[1], 'ro')
plt.text(OH[0] + 0.2, OH[1], 'H', color='red')

# 表示範囲と装飾
plt.xlim(-1, 6)
plt.ylim(-1, 10)
plt.gca().set_aspect('equal', adjustable='box')
plt.title("Projection of OP onto Vector A")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)
plt.legend()
plt.show()

# ------------------------------
# 数値出力 / Print numerical result
# ------------------------------
print(f"ベクトルOHの成分:({OH[0]:.2f}, {OH[1]:.2f})")

お客様に提供する「面積59」ソリューション

import numpy as np
import matplotlib.pyplot as plt

# ==== 三角形の3点を定義 / Define the 3 vertices ====
# 例:点A(1, 1), 点B(5, 1), 点C(3, 4)
A = np.array([1, 1])
B = np.array([5, 1])
C = np.array([3, 4])

# ==== ベクトルの差分 / Compute vectors AB and AC ====
AB = B - A
AC = C - A

# ==== 外積の大きさから面積計算 / Area from cross product magnitude ====
# 面積 = 0.5 * |AB × AC| = 0.5 * |AB_x * AC_y - AB_y * AC_x|
area = 0.5 * np.abs(AB[0] * AC[1] - AB[1] * AC[0])

# ==== 結果表示 / Print the area ====
print(f"3点からなる三角形の面積: {area:.2f} 平方単位")
print(f"Triangle area from given 3 points: {area:.2f} square units")

# ==== プロット / Plot the triangle ====
plt.figure(figsize=(6, 6))

# 三角形の辺を描画 / Draw triangle edges
triangle = np.array([A, B, C, A])  # 最後にAに戻る
plt.plot(triangle[:, 0], triangle[:, 1], 'b-', label='Triangle')
plt.fill(triangle[:, 0], triangle[:, 1], alpha=0.3, color='skyblue')  # 塗りつぶし

# 各点にラベルをつける / Label points
for point, label in zip([A, B, C], ['A', 'B', 'C']):
    plt.scatter(*point, color='red')
    plt.text(point[0]+0.1, point[1]+0.1, f'{label} {tuple(point)}', fontsize=10)

# プロット設定 / Plot settings
plt.title(f"Area of Triangle = {area:.2f} square units")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.grid(True)
plt.axis('equal')
plt.legend()
plt.show()

お客様に提供する「距離69」ソリューション

import numpy as np
import matplotlib.pyplot as plt

# ------------------------------
# 直線の定義 / Define the line y = ax + b
# ------------------------------
a = 1   # 傾き / Slope
b = 0   # 切片 / Intercept

# ------------------------------
# データ点(正常 + ノイズ含む) / Define points
# ------------------------------
np.random.seed(0)
x_points = np.linspace(-5, 5, 30)
y_points = a * x_points + b + np.random.normal(0, 1.0, size=x_points.shape)

# 一部異常点を追加 / Inject anomalies
x_points[5] += 3
y_points[5] += 5
x_points[20] -= 4
y_points[20] -= 6

# ------------------------------
# 点と直線の距離を計算 / Compute distance
# ------------------------------
def point_to_line_distance(x0, y0, a, b):
    """点と直線 y = ax + b の距離 / Distance from (x0,y0) to line"""
    return np.abs(a * x0 - y0 + b) / np.sqrt(a ** 2 + 1)

distances = point_to_line_distance(x_points, y_points, a, b)

# ------------------------------
# 異常検知 / Anomaly Detection
# ------------------------------
threshold = 2.5  # 距離のしきい値 / Threshold
is_anomaly = distances > threshold

# ------------------------------
# プロット / Plotting
# ------------------------------
plt.figure(figsize=(10, 6))

# プロット:直線
x_line = np.linspace(-6, 6, 100)
y_line = a * x_line + b
plt.plot(x_line, y_line, 'k--', label='Line: y = ax + b')

# プロット:正常点
plt.scatter(x_points[~is_anomaly], y_points[~is_anomaly], color='blue', label='Normal')

# プロット:異常点
plt.scatter(x_points[is_anomaly], y_points[is_anomaly], color='red', label='Anomaly')

# 装飾
plt.title("Distance from Points to Line & Anomaly Detection")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)
plt.legend()
plt.show()

# ------------------------------
# 異常点の出力 / Print anomaly info
# ------------------------------
print("異常検知結果 / Detected Anomalies:")
for i, (x0, y0, d) in enumerate(zip(x_points, y_points, distances)):
    if d > threshold:
        print(f"{i}: (x={x0:.2f}, y={y0:.2f}) → 距離 = {d:.2f}(異常)")

お客様に提供する「円70」ソリューション

import numpy as np
import matplotlib.pyplot as plt
import sympy as sp

# -------------------------------------
# 一般式の係数設定: x² + y² + D·x + E·y + F = 0
# 例: x² + y² - 4x + 6y - 12 = 0
# -------------------------------------
D = -4
E = 6
F = -12

# -------------------------------------
# 中心 (h, k) と 半径 r の計算
# -------------------------------------
h = -D / 2
k = -E / 2
r_squared = h**2 + k**2 - F

# 半径
r = sp.sqrt(r_squared)

# 結果表示
print("【円の標準形】")
print(f"(x - {h})² + (y - {k})² = {r_squared}")
print(f"→ 半径 r = {float(r):.2f}")
print(f"→ 中心: ({h}, {k})")

# -------------------------------------
# プロット / Plotting the Circle
# -------------------------------------
theta = np.linspace(0, 2 * np.pi, 400)
x_vals = h + float(r) * np.cos(theta)
y_vals = k + float(r) * np.sin(theta)

plt.figure(figsize=(6, 6))
plt.plot(x_vals, y_vals, label='Circle')
plt.plot(h, k, 'ro', label='Center')
plt.axhline(0, color='gray', linestyle='--')
plt.axvline(0, color='gray', linestyle='--')
plt.title("Circle from General Form")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)
plt.legend()
plt.axis('equal')
plt.show()

お客様に提供する「微分法の計算72」ソリューション

import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
import torch

# --------------------------------------
# シンボリック定義(式の展開と微分)/ Symbolic part
# --------------------------------------
x = sp.Symbol('x')
y_expr = (x**2 + 3*x - 2) * (2*x + 1)
y_expanded = sp.expand(y_expr)
dy_dx = sp.diff(y_expr, x)

print("【関数の展開】")
print("y =", y_expanded)
print("\n【導関数】")
print("dy/dx =", dy_dx)

# --------------------------------------
# 数値化 / Lambdify
# --------------------------------------
y_func = sp.lambdify(x, y_expr, 'numpy')
dy_func = sp.lambdify(x, dy_dx, 'numpy')

# --------------------------------------
# プロット用の x 範囲
# --------------------------------------
x_vals = np.linspace(-5, 3, 500)
y_vals = y_func(x_vals)
dy_vals = dy_func(x_vals)

# サンプルホールド用に離散サンプリング
x_sample = np.linspace(-5, 3, 30)
y_sample = y_func(x_sample)

# デジタル微分(前進差分)/ Digital Differentiation
dy_digital = np.diff(y_sample) / np.diff(x_sample)
x_digital = (x_sample[:-1] + x_sample[1:]) / 2

# --------------------------------------
# PyTorch による自動微分 / Automatic Differentiation
# --------------------------------------
x_torch = torch.tensor(x_vals, requires_grad=True)
y_torch = (x_torch**2 + 3 * x_torch - 2) * (2 * x_torch + 1)
dy_auto = torch.autograd.grad(outputs=y_torch, inputs=x_torch,
                              grad_outputs=torch.ones_like(x_torch),
                              create_graph=True)[0].detach().numpy()

# --------------------------------------
# グラフ描画 / Plotting
# --------------------------------------
plt.figure(figsize=(14, 12))

# 1. 関数と微分曲線
plt.subplot(2, 2, 1)
plt.plot(x_vals, y_vals, label='y(x)', color='blue')
plt.plot(x_vals, dy_vals, label="dy/dx (Symbolic)", color='red')
plt.plot(x_vals, dy_auto, '--', label="dy/dx (AutoDiff)", color='orange')
plt.title("Function and Its Derivative")
plt.xlabel("x")
plt.ylabel("y / dy/dx")
plt.legend()
plt.grid(True)

# 2. 勾配(矢印)を視覚化
plt.subplot(2, 2, 2)
plt.plot(x_vals, y_vals, color='blue')
for i in range(0, len(x_vals), 30):
    x0 = x_vals[i]
    y0 = y_vals[i]
    slope = dy_vals[i]
    dx = 0.5
    dy = slope * dx
    plt.arrow(x0, y0, dx, dy, head_width=0.5, head_length=0.5, fc='orange', ec='orange')
plt.title("Gradient (Tangent Slopes)")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)

# 3. サンプルホールド表示(ステップ的に表示)
plt.subplot(2, 2, 3)
plt.step(x_sample, y_sample, where='mid', label='Sample & Hold', color='purple')
plt.plot(x_vals, y_vals, alpha=0.3, label='y(x)', color='gray')
plt.title("Sample and Hold Representation")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.grid(True)

# 4. デジタル微分(差分による近似)
plt.subplot(2, 2, 4)
plt.plot(x_digital, dy_digital, 'o-', label='Digital Derivative (Δy/Δx)', color='green')
plt.plot(x_vals, dy_vals, alpha=0.5, label='True dy/dx (Symbolic)', color='red')
plt.title("Digital Differentiation")
plt.xlabel("x")
plt.ylabel("dy/dx")
plt.legend()
plt.grid(True)

plt.tight_layout()
plt.show()

お客様に提供する「定積分75」ソリューション

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad
from sympy import symbols, integrate, pprint
import cv2
from sklearn.linear_model import LinearRegression

# -------------------------------
# 二次関数の定義: f(x) = ax^2 + bx + c
# -------------------------------
a, b, c = 1, -2, 1  # f(x) = x^2 - 2x + 1 = (x-1)^2
def f(x):
    return a * x**2 + b * x + c

x_start, x_end = 0, 2

# -------------------------------
# 解析的に分数で計算 / Symbolic integration with fraction output
# -------------------------------
x = symbols('x')
fx = a * x**2 + b * x + c
area_symbolic = integrate(fx, (x, x_start, x_end))  # 定積分 ∫₀² (x-1)^2 dx

print("【解析的な定積分の面積(Exact integral area)】")
print(" 分数表記:")
pprint(area_symbolic)  # 分数で表示
print(f" 小数表記: {float(area_symbolic):.5f}")

# -------------------------------
# 1. 定積分の計算(数値的)/ Analytical definite integral
# -------------------------------
area_exact, _ = quad(f, x_start, x_end)

# -------------------------------
# 2. 区分求積法による近似 / Numerical integration
# -------------------------------
N = 50  # 分割数
x_rect = np.linspace(x_start, x_end, N+1)
x_mid = (x_rect[:-1] + x_rect[1:]) / 2  # サンプルホールド (中点)
dx = (x_end - x_start) / N
area_approx = np.sum(f(x_mid) * dx)

# -------------------------------
# 3. プロットによる可視化
# -------------------------------
x_vals = np.linspace(x_start, x_end, 400)
y_vals = f(x_vals)

plt.figure(figsize=(10, 6))
plt.plot(x_vals, y_vals, 'b', label='f(x) = x² - 2x + 1')
plt.bar(x_mid, f(x_mid), width=dx, alpha=0.3, align='center', edgecolor='black', label='Rectangles')
plt.fill_between(x_vals, y_vals, where=(x_vals >= x_start) & (x_vals <= x_end), color='orange', alpha=0.3, label='Area under curve')
plt.title('Definite Integral and Riemann Sum')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend()
plt.grid(True)
plt.show()

# -------------------------------
# 画像処理での面積計算(疑似画像)/ Simulated image-based area calculation
# -------------------------------
image = np.zeros((100, 100), dtype=np.uint8)
cv2.rectangle(image, (20, 30), (80, 70), 255, -1)  # 白い矩形を描画
image_area = np.sum(image == 255)

# -------------------------------
# 機械学習モデルによる面積近似(線形回帰)/ ML model area approximation
# -------------------------------
X = np.linspace(0, 2, 100).reshape(-1, 1)
y = f(X).ravel() + np.random.normal(0, 0.05, size=100)  # ノイズ付き
model = LinearRegression()
model.fit(X, y)
y_pred = model.predict(X)
ml_area = np.trapz(y_pred, x=X.ravel())

# -------------------------------
# 結果表示 / Print all results
# -------------------------------
results = {
    "解析的定積分(小数)": round(area_exact, 5),
    "区分求積法による面積": round(area_approx, 5),
    "画像処理での面積(白ピクセル数)": int(image_area),
    "機械学習モデルによる面積": round(ml_area, 5)
}
results

お客様に提供する「指数法則77と対数の定義78」ソリューション

import numpy as np
import matplotlib.pyplot as plt

# --------------------------------------
# x: 倍率(1/10 ~ 100倍)
# --------------------------------------
x = np.linspace(0.1, 100, 1000)

# --------------------------------------
# 計算(対数とdB)/ Compute log & dB
# --------------------------------------
log10_x = np.log10(x)             # 常用対数
log2_x = np.log2(x)               # 2を底とする対数
ln_x = np.log(x)                  # 自然対数

db_power = 10 * log10_x           # 電力比のdB
db_voltage = 20 * log10_x         # 電圧比のdB

# --------------------------------------
# グラフ描画
# --------------------------------------
plt.figure(figsize=(14, 8))

# 1. 対数関数
plt.subplot(2, 2, 1)
plt.plot(x, log10_x, label='log₁₀(x)', color='blue')
plt.plot(x, log2_x, label='log₂(x)', color='green')
plt.plot(x, ln_x, label='ln(x)', color='orange')
plt.title("Logarithmic Functions")
plt.xlabel("x (倍率 / Multiplication factor)")
plt.ylabel("log(x)")
plt.grid(True)
plt.legend()

# 2. 指数関数
x_exp = np.linspace(-2, 4, 500)
plt.subplot(2, 2, 2)
plt.plot(x_exp, 10 ** x_exp, label='10ˣ', color='purple')
plt.plot(x_exp, 2 ** x_exp, label='', color='red')
plt.title("Exponential Functions")
plt.xlabel("x")
plt.ylabel("")
plt.grid(True)
plt.legend()

# 3. dB(電力比)
plt.subplot(2, 2, 3)
plt.plot(x, db_power, label='dB (Power) = 10 log₁₀(x)', color='navy')
plt.title("Decibels: Power Ratio")
plt.xlabel("Power Ratio (x)")
plt.ylabel("dB")
plt.grid(True)
plt.legend()

# 4. dB(電圧比)
plt.subplot(2, 2, 4)
plt.plot(x, db_voltage, label='dB (Voltage) = 20 log₁₀(x)', color='darkred')
plt.title("Decibels: Voltage Ratio")
plt.xlabel("Voltage Ratio (x)")
plt.ylabel("dB")
plt.grid(True)
plt.legend()

plt.tight_layout()
plt.show()


import numpy as np
import matplotlib.pyplot as plt

# 時間の定義
t = np.linspace(0, 10, 1000)  # 0から10秒の範囲で1000点

# 一次遅れ系のパラメータ
tau = 1  # 時定数
u = np.ones_like(t)  # 入力信号(単位ステップ入力)

# 出力の計算:一次遅れ系の解
y = 1 - np.exp(-t / tau)

# シグモイド関数の定義
def sigmoid(x):
    return 1 / (1 + np.exp(-x))

# シグモイド関数を適用した出力
y_sigmoid = sigmoid(y)

# プロット
plt.figure(figsize=(12, 6))

# 一次遅れのプロット
plt.subplot(1, 2, 1)
plt.plot(t, y, label="Exponential 1st-order Response", color='blue')
plt.title("Exponential First-Order Response")
plt.xlabel("Time (t)")
plt.ylabel("Output y(t)")
plt.grid(True)
plt.legend()

# シグモイド活性化関数のプロット
plt.subplot(1, 2, 2)
plt.plot(t, y_sigmoid, label="Sigmoid Activation", color='red')
plt.title("Sigmoid Activation of Output")
plt.xlabel("Time (t)")
plt.ylabel("Sigmoid Output")
plt.grid(True)
plt.legend()

plt.tight_layout()
plt.show()

お客様に提供する「階乗81」ソリューション

# ------------------------------------------
# 毎回の掛け算ステップと結果を表示する階乗計算
# Show step-by-step multiplication and result
# ------------------------------------------

def factorial_step_print(n):
    """階乗の各ステップを表示 / Show each multiplication step"""
    result = 1
    print(f"{n}! を計算します / Calculating {n}! step-by-step:\n")
    
    for i in range(1, n + 1):
        result *= i
        print(f"{i} をかける → 現在の結果 = {result}")
    
    print(f"\n最終結果 / Final result: {n}! = {result}")
    return result

# --------------------------
# 実行 / Run for example N = 7
# --------------------------
N = 7
factorial_step_print(N)

お客様に提供する「CとP82」ソリューション

import math

# ---------------------------
# 入力値設定
# ---------------------------
n = 6  # 総数 n
r = 3  # 選ぶ数 r
a, b = 2, 1  # 重複を除きたい個数の例(例えば2つが同じ、もう1つも同じ)

# ---------------------------
# 順列: nPr(順番あり、区別あり)
# ---------------------------
nPr = math.perm(n, r)  # Python 3.8以降
# もしくは: nPr = math.factorial(n) // math.factorial(n - r)

# ---------------------------
# 組合せ: nCr(順番なし、区別なし)
# ---------------------------
nCr = math.comb(n, r)  # Python 3.8以降
# もしくは: nCr = math.factorial(n) // (math.factorial(r) * math.factorial(n - r))

# ---------------------------
# 重複のある順列: a!, b! で割る
# ---------------------------
duplicated = math.perm(n, r) // (math.factorial(a) * math.factorial(b))

# ---------------------------
# 出力
# ---------------------------
print("【順列・組合せの計算】")
print(f"n = {n}, r = {r}")
print(f"nPr(順番あり・区別あり)= {nPr}")
print(f"nCr(順番なし・区別なし)= {nCr}")
print(f"重複あり(a={a}, b={b} のとき)= {duplicated}")

お客様に提供する「平均値分散89」ソリューション

import numpy as np
import matplotlib.pyplot as plt
from sklearn.neural_network import MLPRegressor
from sklearn.preprocessing import StandardScaler

# -----------------------------
# データ定義 / Define sample data
# -----------------------------
np.random.seed(0)
x = np.linspace(0, 10, 20)
y = 2 * x + 1 + np.random.normal(scale=3, size=x.shape)  # ノイズあり線形データ

# -----------------------------
# 平均と分散 / Mean and Variance
# -----------------------------
x_mean = np.mean(x)
y_mean = np.mean(y)
x_var = np.var(x)
y_var = np.var(y)

print("【平均と分散 / Mean and Variance】")
print(f"x̄ = {x_mean:.2f}, Var(x) = {x_var:.2f}")
print(f"ȳ = {y_mean:.2f}, Var(y) = {y_var:.2f}")

# -----------------------------
# 最小二乗法 / Least Squares (Linear Regression)
# -----------------------------
a, b = np.polyfit(x, y, deg=1)
y_linear = a * x + b

# -----------------------------
# ニューラルネット回帰 / Neural Network Regression
# -----------------------------
# 入力は2Dに変換 + 標準化
x_2d = x.reshape(-1, 1)
scaler = StandardScaler()
x_scaled = scaler.fit_transform(x_2d)

# ニューラルネット(1 hidden layer, 10 units)
model = MLPRegressor(hidden_layer_sizes=(10,), max_iter=5000, random_state=0)
model.fit(x_scaled, y)

# 推論用データ
x_test = np.linspace(0, 10, 200).reshape(-1, 1)
x_test_scaled = scaler.transform(x_test)
y_nn = model.predict(x_test_scaled)

# -----------------------------
# プロット / Plotting
# -----------------------------
plt.figure(figsize=(12, 6))
plt.scatter(x, y, label='Data Points', color='blue')
plt.plot(x, y_linear, label=f'Least Squares (y = {a:.2f}x + {b:.2f})', color='red')
plt.plot(x_test, y_nn, label='Neural Net Regression', color='green')
plt.axhline(y_mean, linestyle='--', color='gray', label=f'Mean of y = {y_mean:.2f}')

plt.title("Least Squares vs Neural Network Regression")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)
plt.legend()
plt.show()


終わりに

今回の学習では、「合格(うか)る計算数学 I・A・II・B」を通じて、Pythonコードによる数学演習AIとの対話による理解の深化、工学的シミュレーションまで、幅広いアプローチを体験していただきました。

一見すると、まったく関係のないように見えるAI関連のコードや工学的なツールが途中に登場しましたが、それこそが本プラットフォームの強みです。
なぜなら、現代における数学の活用シーンは単なる公式の暗記に留まらずデータ分析・回路設計・自動化・最適化といった実社会のあらゆる分野とつながっているからです。

私たちは単一の教材や単一のツールに閉じることなく、
「数学 × プログラミング × AI × 工学」を掛け合わせたトータル・ラーニング・ソリューションを提供します。


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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?