Wolfram|AlphaとPythonコード


```
# Arithmetic Sequence: 等差数列を生成する関数
def arithmetic_sequence(a, d, n):
    """
    Generate an arithmetic sequence (等差数列を生成)
    :param a: First term (初項)
    :param d: Common difference (公差)
    :param n: Number of terms (項数)
    :return: List of arithmetic sequence (等差数列のリスト)
    """
    return [a + d * i for i in range(n)]

# Geometric Sequence: 等比数列を生成する関数
def geometric_sequence(a, r, n):
    """
    Generate a geometric sequence (等比数列を生成)
    :param a: First term (初項)
    :param r: Common ratio (公比)
    :param n: Number of terms (項数)
    :return: List of geometric sequence (等比数列のリスト)
    """
    return [a * r**i for i in range(n)]

# Examples of arithmetic sequences (等差数列の例)
print("Arithmetic Sequences (等差数列):")
arithmetic_seq_1 = arithmetic_sequence(1, 1, 10)  # First term 1, common difference 1, 10 terms (初項1, 公差1, 10項)
arithmetic_seq_2 = arithmetic_sequence(3, 2, 10)  # First term 3, common difference 2, 10 terms (初項3, 公差2, 10項)
print(f"First term 1, Common difference 1: {arithmetic_seq_1}")
print(f"First term 3, Common difference 2: {arithmetic_seq_2}")

# Examples of geometric sequences (等比数列の例)
print("\nGeometric Sequences (等比数列):")
geometric_seq_1 = geometric_sequence(1, 2, 10)  # First term 1, common ratio 2, 10 terms (初項1, 公比2, 10項)
geometric_seq_2 = geometric_sequence(5, 3, 10)  # First term 5, common ratio 3, 10 terms (初項5, 公比3, 10項)
geometric_seq_3 = geometric_sequence(1, -1, 10) # First term 1, common ratio -1, 10 terms (初項1, 公比-1, 10項)
print(f"First term 1, Common ratio 2: {geometric_seq_1}")
print(f"First term 5, Common ratio 3: {geometric_seq_2}")
print(f"First term 1, Common ratio -1: {geometric_seq_3}")

```


```
import numpy as np
import matplotlib.pyplot as plt

# 定義域の設定（x > 0 を考慮）
x = np.linspace(0.1, 10, 500)  # x > 0 の範囲（0.1から10まで）

# 関数の定義
y = x**2 * np.log(x)

# 通常のグラフ
plt.figure(figsize=(8, 6))
plt.plot(x, y, label=r"$x^2 \log x$", color="blue")
plt.title("Graph of $x^2 \log x$")
plt.xlabel("x")
plt.ylabel("y")
plt.axhline(0, color="black", linewidth=0.8, linestyle="--")
plt.grid()
plt.legend()
plt.show()

# x 軸対数スケールのグラフ
plt.figure(figsize=(8, 6))
plt.plot(x, y, label=r"$x^2 \log x$", color="green")
plt.xscale("log")  # x 軸を対数スケールに変更
plt.title("Graph of $x^2 \log x$ (Logarithmic x-axis)")
plt.xlabel("x (log scale)")
plt.ylabel("y")
plt.axhline(0, color="black", linewidth=0.8, linestyle="--")
plt.grid()
plt.legend()
plt.show()

# 両対数スケールのグラフ
plt.figure(figsize=(8, 6))
plt.plot(x, y, label=r"$x^2 \log x$", color="red")
plt.xscale("log")  # x 軸を対数スケールに変更
plt.yscale("log")  # y 軸を対数スケールに変更
plt.title("Graph of $x^2 \log x$ (Log-Log Scale)")
plt.xlabel("x (log scale)")
plt.ylabel("y (log scale)")
plt.grid()
plt.legend()
plt.show()

```



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

# Define variables
x, k = sp.symbols('x k')

# Define the function
f = x**2 * (k - x)

# Compute the derivative
f_derivative = sp.diff(f, x)

# Solve f(x) = 0 (roots of the function)
f_zeros = sp.solve(f, x)

# Solve f'(x) = 0 (roots of the derivative)
f_derivative_zeros = sp.solve(f_derivative, x)

# Display the solutions (symbolic form)
print("Solutions where f(x) = 0 (symbolic):")
print(f_zeros)

print("\nSolutions where f'(x) = 0 (symbolic):")
print(f_derivative_zeros)

# Substitute a specific value for k (e.g., k = 10)
k_value = 10

# Evaluate symbolic solutions with specific k (keep symbolic roots)
f_zeros_symbolic = [sol.subs(k, k_value) for sol in f_zeros]
f_derivative_zeros_symbolic = [sol.subs(k, k_value) for sol in f_derivative_zeros]

print("\nSolutions where f(x) = 0 (with k = 10):")
print(f_zeros_symbolic)

print("\nSolutions where f'(x) = 0 (with k = 10):")
print(f_derivative_zeros_symbolic)

# Convert symbolic functions to numerical for plotting
f_numeric = sp.lambdify(x, f.subs(k, k_value), 'numpy')
f_derivative_numeric = sp.lambdify(x, f_derivative.subs(k, k_value), 'numpy')

# Define x range
x_values = np.linspace(0, k_value, 500)

# Compute the function and its derivative
f_values = f_numeric(x_values)
f_derivative_values = f_derivative_numeric(x_values)

# Plot the function and its derivative
plt.figure(figsize=(8, 6))
plt.plot(x_values, f_values, label="f(x) = $x^2(k-x)$", color="blue")
plt.plot(x_values, f_derivative_values, label="f'(x)", color="red", linestyle="--")
plt.axhline(0, color="black", linewidth=0.8, linestyle=":")
plt.scatter([float(sol) for sol in f_zeros_symbolic], [0]*len(f_zeros_symbolic), color='green', label="f(x) = 0")
plt.scatter([float(sol) for sol in f_derivative_zeros_symbolic], [0]*len(f_derivative_zeros_symbolic), color='purple', label="f'(x) = 0")
plt.title("Function and its Derivative with Zeros")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.grid()
plt.show()
```

```
import numpy as np
import matplotlib.pyplot as plt

# 1. Integer, Fraction, Decimal, Exponentiation Calculations
integer_example = 5 * 4  # Integer multiplication
fraction_example = 3/4  # Fraction
decimal_example = 0.25  # Decimal
exponentiation_example = 2**3  # Exponentiation (2 raised to the power of 3)

print(f"Integer Example: {integer_example}")
print(f"Fraction Example: {fraction_example}")
print(f"Decimal Example: {decimal_example}")
print(f"Exponentiation Example: {exponentiation_example}")

# 2. Equation and Inequality (Solving equation: x + 3 = 7)
from sympy import symbols, Eq, solve
x = symbols('x')
equation = Eq(x + 3, 7)  # x + 3 = 7
solution = solve(equation, x)
print(f"Solution to the equation x + 3 = 7: x = {solution}")

# Inequality: x > 5
inequality = x > 5
print(f"Inequality x > 5 is: {inequality}")

# 3. Basic Algebraic Operations (Addition, Subtraction, Multiplication, Division)
a, b = 7, 2
addition = a + b
subtraction = a - b
multiplication = a * b
division = a / b

print(f"Addition: {addition}")
print(f"Subtraction: {subtraction}")
print(f"Multiplication: {multiplication}")
print(f"Division: {division}")

# 4. Expanding and Factoring Expressions (Using symbolic math)
from sympy import expand, factor
expression = (x + 2)*(x + 3)  # Expand (x + 2)(x + 3)
expanded_expression = expand(expression)
factored_expression = factor(expanded_expression)
print(f"Expanded expression: {expanded_expression}")
print(f"Factored expression: {factored_expression}")

# 5. Functions and Graphs

# 5.1 Linear Function (y = 2x + 1)
def linear_function(x):
    return 2 * x + 1

# 5.2 Quadratic Function (y = x^2 - 4x + 3)
def quadratic_function(x):
    return x**2 - 4*x + 3

# 5.3 Inverse Proportional Function (y = 1/x)
def inverse_proportional_function(x):
    return 1/x

# 5.4 Exponential Function (y = 2^x)
def exponential_function(x):
    return 2**x

# 5.5 Logarithmic Function (y = log(x))
def logarithmic_function(x):
    return np.log(x)

# Create an array of x values
x_values = np.linspace(-5, 5, 400)
x_values_for_log_exp = np.linspace(0.1, 5, 400)  # log and exponential cannot handle x = 0

# Plot functions
plt.figure(figsize=(10, 8))

# Linear Function Plot
plt.subplot(3, 2, 1)
plt.plot(x_values, linear_function(x_values), label="y = 2x + 1", color="blue")
plt.title('Linear Function: y = 2x + 1')
plt.grid(True)

# Quadratic Function Plot
plt.subplot(3, 2, 2)
plt.plot(x_values, quadratic_function(x_values), label="y = x^2 - 4x + 3", color="green")
plt.title('Quadratic Function: y = x^2 - 4x + 3')
plt.grid(True)

# Inverse Proportional Function Plot
plt.subplot(3, 2, 3)
plt.plot(x_values[x_values != 0], inverse_proportional_function(x_values[x_values != 0]), label="y = 1/x", color="red")
plt.title('Inverse Proportional Function: y = 1/x')
plt.grid(True)

# Exponential Function Plot
plt.subplot(3, 2, 4)
plt.plot(x_values_for_log_exp, exponential_function(x_values_for_log_exp), label="y = 2^x", color="purple")
plt.title('Exponential Function: y = 2^x')
plt.grid(True)

# Logarithmic Function Plot
plt.subplot(3, 2, 5)
plt.plot(x_values_for_log_exp, logarithmic_function(x_values_for_log_exp), label="y = log(x)", color="orange")
plt.title('Logarithmic Function: y = log(x)')
plt.grid(True)

plt.tight_layout()
plt.show()
```

```
import math

# Function to convert degrees to radians
def degrees_to_radians(degrees):
    return degrees * (math.pi / 180)

# Function to convert radians to degrees
def radians_to_degrees(radians):
    return radians * (180 / math.pi)

# Example usage
degrees = 180
radians = degrees_to_radians(degrees)
converted_degrees = radians_to_degrees(radians)

print(f"{degrees} degrees is equal to {radians:.2f} radians.")
print(f"{radians:.2f} radians is equal to {converted_degrees:.2f} degrees.")

```

```
# Define the number
number = 59049

# Calculate the 5th root
fifth_root = number ** (1/5)

# Display the result
print(f"The 5th root of {number} is {fifth_root:.2f}")
```

```
from scipy.optimize import fsolve

# Define the function
def f(x):
    return x**2 - 4

# Find the root
root = fsolve(f, x0=1)  # Initial guess x0 = 1
print(f"Root: {root[0]}")

```
```
import matplotlib.pyplot as plt
import numpy as np

# Line 1: Passes through (1, 6) with a slope of 4
x1, y1, m1 = 1, 6, 4  # point (1,6) and slope 4
# Equation: y = m1*x + b1
b1 = y1 - m1 * x1  # Calculate intercept
line1_eq = f"y = {m1}x + {b1}"

# Line 2: Passes through (6, 1) with an intercept of -5
x2, y2, b2 = 6, 1, -5  # point (6,1) and intercept -5
# Equation: y = m2*x + b2
m2 = (y2 - b2) / x2  # Calculate slope
line2_eq = f"y = {m2:.2f}x + {b2}"

# Define x values for plotting
x = np.linspace(-10, 10, 500)

# Calculate y values for both lines
y1 = m1 * x + b1
y2 = m2 * x + b2

# Plot the lines
plt.figure(figsize=(8, 6))
plt.plot(x, y1, label=f"Line 1: {line1_eq}", color="blue")
plt.plot(x, y2, label=f"Line 2: {line2_eq}", color="red")

# Plot the points
plt.scatter([1, 6], [6, 1], color="black", label="Given Points")
plt.text(1, 6, "(1,6)", fontsize=10, ha='right')
plt.text(6, 1, "(6,1)", fontsize=10, ha='right')

# Add grid, legend, and labels
plt.axhline(0, color='black', linewidth=0.5)
plt.axvline(0, color='black', linewidth=0.5)
plt.grid(True)
plt.title("Lines Based on Given Conditions")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.show()
```

```
import matplotlib.pyplot as plt
import math

# Coordinates of the points
x1, y1 = 1, 2
x2, y2 = 4, 6

# Calculate the distance
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

# Plot the points
plt.figure(figsize=(6, 6))
plt.plot([x1, x2], [y1, y2], 'ro-', label=f"Distance: {distance:.2f}")
plt.text(x1, y1, f"({x1}, {y1})", fontsize=10, ha='right')
plt.text(x2, y2, f"({x2}, {y2})", fontsize=10, ha='left')

# Add grid and labels
plt.grid(True)
plt.title("Distance Between Points")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.legend()
plt.show()
```

https://ja.wolframalpha.com/input?i=x%5E4%2B2x%5E3y-2xy%5E3-y%5E4%E3%82%92%E5%9B%A0%E6%95%B0%E5%88%86%E8%A7%A3%E3%81%99%E3%82%8B

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

# Define the variables
x, y = sp.symbols('x y')

# Define the polynomial
polynomial = x**4 + 2*x**3*y - 2*x*y**3 - y**4

# Factorize the polynomial
factors = sp.factor(polynomial)
print(f"Factorized polynomial: {factors}")

# Convert the polynomial to a lambda function for plotting
f_lambda = sp.lambdify((x, y), polynomial, 'numpy')

# Generate a grid of x and y values
x_vals = np.linspace(-2, 2, 400)
y_vals = np.linspace(-2, 2, 400)
x_grid, y_grid = np.meshgrid(x_vals, y_vals)

# Evaluate the polynomial on the grid
z_vals = f_lambda(x_grid, y_grid)

# Plot the polynomial
plt.figure(figsize=(8, 6))
plt.contourf(x_grid, y_grid, z_vals, levels=50, cmap='viridis')
plt.colorbar(label='Polynomial Value')
plt.title(r"$x^4 + 2x^3y - 2xy^3 - y^4$")
plt.xlabel('x')
plt.ylabel('y')
plt.grid(True)
plt.show()


```
https://ja.wolframalpha.com/input?i=y%3D-x%5E2%2B2x%2B8%E3%81%AE%E9%A0%82%E7%82%B9%E3%81%AE%E5%BA%A7%E6%A8%99


```
import numpy as np
import matplotlib.pyplot as plt

# Define the coefficients of the quadratic equation
a = -1  # Coefficient of x^2
b = 2   # Coefficient of x
c = 8   # Constant term

# Calculate the vertex
x_vertex = -b / (2 * a)
y_vertex = a * x_vertex**2 + b * x_vertex + c
vertex = (x_vertex, y_vertex)
print(f"Vertex of the parabola: {vertex}")

# Define the quadratic function
def quadratic(x):
    return a * x**2 + b * x + c

# Generate x values for plotting
x_vals = np.linspace(-2, 4, 500)
y_vals = quadratic(x_vals)

# Plot the parabola and the vertex
plt.figure(figsize=(8, 6))
plt.plot(x_vals, y_vals, label=r"$y = -x^2 + 2x + 8$", color="blue")
plt.scatter(*vertex, color="red", label="Vertex", zorder=5)
plt.title("Parabola and its Vertex")
plt.xlabel("x")
plt.ylabel("y")
plt.axhline(0, color="black", linewidth=0.5, linestyle="--")
plt.axvline(0, color="black", linewidth=0.5, linestyle="--")
plt.legend()
plt.grid(True)
plt.show()

```

https://ja.wolframalpha.com/input?i=1%2F%283-%E2%88%9A5%29%E3%81%AE%E5%88%86%E6%AF%8D%E3%82%92%E6%9C%89%E7%90%86%E5%8C%96
```
import sympy as sp

# Define the expression
x = sp.Symbol('x')
expr = 1 / (3 - sp.sqrt(5))

# Rationalize the denominator
rationalized_expr = sp.simplify(expr)
print(f"Original expression: {expr}")
print(f"Rationalized expression: {rationalized_expr}")


```

https://ja.wolframalpha.com/input?i=2%7Cx%5E2%2B2x-3%7C-3%7Cx-1%7C%3E2x%2B3%E3%81%AE%E8%A7%A3


```
import sympy as sp

# Define the variable
x = sp.Symbol('x')

# Define the inequality
inequality = 2 * sp.Abs(x**2 + 2*x - 3) - 3 * sp.Abs(x - 1) - (2*x + 3) > 0

# Solve the inequality
solution = sp.solveset(inequality, x, domain=sp.S.Reals)

# Print the solution
print(f"Solution to the inequality: {solution}")

```
https://ja.wolframalpha.com/input?i=0%E2%89%A6%CE%B8%E2%89%A62%CF%80%E3%81%AE%E3%81%A8%E3%81%8D%EF%BC%8Csin%5E3%28%CE%B8%29%2Bcos%5E3%28%CE%B8%29%E3%81%AE%E6%9C%80%E5%A4%A7%E5%80%A4%E3%81%A8%E6%9C%80%E5%B0%8F%E5%80%A4



```
import sympy as sp

# Define the variable
theta = sp.Symbol('theta', real=True)

# Define the function
f = sp.sin(theta)**3 + sp.cos(theta)**3

# Calculate the derivative
df = sp.diff(f, theta)

# Solve for critical points
critical_points = sp.solveset(df, theta, domain=sp.Interval(0, 2*sp.pi))

# Evaluate the function at critical points and endpoints
points = list(critical_points) + [0, 2*sp.pi]
values = [f.subs(theta, point).evalf() for point in points]

# Find the maximum and minimum values
max_value = max(values)
min_value = min(values)

print(f"Critical points: {critical_points}")
print(f"Function values at critical points and endpoints: {values}")
print(f"Maximum value: {max_value}")
print(f"Minimum value: {min_value}")

```


https://ja.wolframalpha.com/input?i=f%28x%29%3Dlog%28x%29%2Fx%5E2%E3%81%AE%E6%9C%80%E5%A4%A7%E5%80%A4


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

# Define the variable and function
x = sp.Symbol('x', positive=True, real=True)  # x > 0
f = sp.log(x) / x**2

# Calculate the derivative
df = sp.diff(f, x)

# Solve for critical points
critical_points = sp.solveset(df, x, domain=sp.Interval(0.1, sp.oo))

# Find the maximum value
critical_values = [f.subs(x, point).evalf() for point in critical_points]
max_value = max(critical_values)
max_point = [point for point in critical_points if f.subs(x, point).evalf() == max_value][0]

print(f"Critical points: {critical_points}")
print(f"Maximum value: {max_value} at x = {max_point}")

# Plot the function
x_vals = np.linspace(0.1, 5, 500)  # Avoid x = 0 for logarithm
y_vals = np.log(x_vals) / x_vals**2

plt.figure(figsize=(8, 6))
plt.plot(x_vals, y_vals, label=r"$f(x) = \frac{\log(x)}{x^2}$", color="blue")
plt.scatter([float(max_point)], [float(max_value)], color="red", label="Maximum Point", zorder=5)
plt.axhline(0, color="black", linewidth=0.5, linestyle="--")
plt.axvline(float(max_point), color="red", linestyle="--", label=f"x = {float(max_point):.2f}")
plt.title("Function and Maximum Point")
plt.xlabel("x")
plt.ylabel("f(x)")
plt.grid(True)
plt.legend()
plt.show()

```



```
import sympy as sp

# Define the variable
x = sp.Symbol('x')

# Define the functions
f = x**4 * sp.sin(x)
g = x**3 - x + 3

# Compute the derivative of x^4 * sin(x)
derivative_f = sp.diff(f, x)
print(f"Derivative of x^4 * sin(x): {derivative_f}")

# Compute the definite integral of x^3 - x + 3 from 0 to 2
definite_integral_g = sp.integrate(g, (x, 0, 2))
print(f"Definite integral of (x^3 - x + 3) from 0 to 2: {definite_integral_g}")

```


https://ja.wolframalpha.com/input?i=x%E3%81%8C0%E3%81%AB%E8%BF%91%E4%BB%98%E3%81%8F%E3%81%A8%E3%81%8D%E3%81%AE+%28sin+x+-+x%29%2Fx%5E3%E3%81%AE%E6%A5%B5%E9%99%90


```
import sympy as sp

# Define the variable
x = sp.Symbol('x')

# Define the function
expr = (sp.sin(x) - x) / x**3

# Compute the limit as x approaches 0
limit_expr = sp.limit(expr, x, 0)
print(f"Limit of (sin(x) - x) / x^3 as x -> 0: {limit_expr}")

```


```
import sympy as sp

# Define the variable
z = sp.Symbol('z')

# Define the equation
equation = z**6 + 27

# Solve the equation
solutions = sp.solveset(equation, z, domain=sp.S.Complexes)

# Print the solutions
print(f"Complex solutions of z^6 + 27 = 0: {solutions}")

```







```
# Generate the sequence of squares
n_terms = 10  # Number of terms to generate
sequence = [n**2 for n in range(1, n_terms + 1)]

# Print the sequence
print(f"The first {n_terms} terms of the sequence are: {sequence}")

```




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

# Define the vectors
vector1 = np.array([1, 3, -1])
vector2 = np.array([-2, 1, 6])
vector_sum = vector1 + vector2

# Create a 3D plot
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')

# Plot vector1
ax.quiver(0, 0, 0, vector1[0], vector1[1], vector1[2], color='blue', label='(1, 3, -1)', arrow_length_ratio=0.1)

# Plot vector2
ax.quiver(0, 0, 0, vector2[0], vector2[1], vector2[2], color='green', label='(-2, 1, 6)', arrow_length_ratio=0.1)

# Plot vector_sum
ax.quiver(0, 0, 0, vector_sum[0], vector_sum[1], vector_sum[2], color='red', label='Sum (-1, 4, 5)', arrow_length_ratio=0.1)

# Set plot limits
ax.set_xlim([-3, 3])
ax.set_ylim([-3, 5])
ax.set_zlim([-3, 7])

# Set labels and legend
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('Vector Addition in 3D Space')
ax.legend()

# Show the plot
plt.show()

```




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

# Define the vectors
vector1 = np.array([8, 3, -1])  # (8i + 3j - k)
vector2 = np.array([1, -1, 2])  # (i - j + 2k)

# Compute the cross product
cross_product = np.cross(vector1, vector2)

# Print the cross product
print(f"Cross product of (8i + 3j - k) and (i - j + 2k): {cross_product}")

# Create a 3D plot
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')

# Plot vector1
ax.quiver(0, 0, 0, vector1[0], vector1[1], vector1[2], color='blue', label='(8i + 3j - k)', arrow_length_ratio=0.1)

# Plot vector2
ax.quiver(0, 0, 0, vector2[0], vector2[1], vector2[2], color='green', label='(i - j + 2k)', arrow_length_ratio=0.1)

# Plot the cross product
ax.quiver(0, 0, 0, cross_product[0], cross_product[1], cross_product[2], color='red', label='Cross Product', arrow_length_ratio=0.1)

# Set plot limits
ax.set_xlim([-20, 20])
ax.set_ylim([-20, 20])
ax.set_zlim([-20, 20])

# Set labels and legend
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('Cross Product of Two Vectors')
ax.legend()

# Show the plot
plt.show()

```



```
import math

# Function to calculate GCD
def compute_gcd(a, b):
    return math.gcd(a, b)

# Function to calculate LCM
def compute_lcm(a, b):
    return abs(a * b) // compute_gcd(a, b)  # LCM formula: |a * b| / GCD(a, b)

# Input numbers
num1 = 12
num2 = 18

# Calculate GCD and LCM
gcd_result = compute_gcd(num1, num2)
lcm_result = compute_lcm(num1, num2)

# Output the results
print(f"The GCD of {num1} and {num2} is: {gcd_result}")
print(f"The LCM of {num1} and {num2} is: {lcm_result}")


```




```
import numpy as np
import matplotlib.pyplot as plt

# Define the system of linear equations
# Example: 
# 2x + y = 5
# x - y = 1
A = np.array([[2, 1],  # Coefficients of x and y for the first equation
              [1, -1]])  # Coefficients of x and y for the second equation
B = np.array([5, 1])  # Constants on the right-hand side

# Solve the system of equations Ax = B
solution = np.linalg.solve(A, B)
x, y = solution

print("Solution:")
print(f"x = {x}, y = {y}")

# Plot the equations and the solution
x_vals = np.linspace(-1, 5, 500)  # Range of x values for plotting
y1 = (5 - 2 * x_vals)  # Rearrange first equation: y = (5 - 2x)
y2 = (x_vals - 1)      # Rearrange second equation: y = (x - 1)

plt.figure(figsize=(8, 6))
plt.plot(x_vals, y1, label="2x + y = 5", color="blue")
plt.plot(x_vals, y2, label="x - y = 1", color="red")
plt.scatter(x, y, color="black", label=f"Solution: ({x:.2f}, {y:.2f})", zorder=5)
plt.axhline(0, color="black", linewidth=0.5, linestyle="--")
plt.axvline(0, color="black", linewidth=0.5, linestyle="--")
plt.grid(color="gray", linestyle="--", linewidth=0.5)
plt.title("Graphical Solution of Linear Equations")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.show()


```




```
import numpy as np
import matplotlib.pyplot as plt

# Define the Gaussian function
def gaussian(x):
    return np.exp(-x**2)

# Analytical Fourier Transform result
def analytical_ft(w):
    return np.exp(-w**2 / 4) / np.sqrt(2)

# Define the range and sampling parameters
x = np.linspace(-10, 10, 2048)  # Range of x values
dx = x[1] - x[0]  # Sampling interval in x
f_x = gaussian(x)  # Evaluate the Gaussian function

# Compute the FFT of the Gaussian function
fft_gaussian = np.fft.fft(f_x)  # FFT computation
fft_gaussian = np.fft.fftshift(fft_gaussian)  # Shift the zero frequency to the center
freq = np.fft.fftfreq(len(x), dx)  # Frequency axis
freq = np.fft.fftshift(freq)  # Shift zero frequency to center

# Scale FFT by the factor for continuous Fourier Transform
fft_gaussian_scaled = fft_gaussian * dx / np.sqrt(2 * np.pi)

# Compute the analytical Fourier Transform for comparison
analytical_values = analytical_ft(2 * np.pi * freq)  # Convert FFT frequencies to angular frequency

# Plot the original Gaussian function
plt.figure(figsize=(12, 8))
plt.subplot(2, 1, 1)
plt.plot(x, f_x, label="Gaussian $e^{-x^2}$", color="blue")
plt.title("Original Gaussian Function")
plt.xlabel("x")
plt.ylabel("Amplitude")
plt.grid()
plt.legend()

# Plot the magnitude of the FFT vs Analytical Fourier Transform
plt.subplot(2, 1, 2)
plt.plot(freq, np.abs(fft_gaussian_scaled), label="FFT of Gaussian", color="blue")
plt.plot(freq, analytical_values, label="Analytical Fourier Transform", color="red", linestyle="--")
plt.title("Fourier Transform of $e^{-x^2}$")
plt.xlabel("Frequency (Hz)")
plt.ylabel("Amplitude")
plt.grid()
plt.legend()

plt.tight_layout()
plt.show()

```
```

import numpy as np
import matplotlib.pyplot as plt

# Define the range for t
t = np.linspace(0, 2 * np.pi, 1000)

# Parametric equations
x = np.sin(10 * t)
y = np.sin(8 * t)

# Plot the parametric curve
plt.figure(figsize=(8, 6))
plt.plot(x, y, label=r"$x = \sin(10t), y = \sin(8t)$")
plt.title("Parametric Plot of (sin(10t), sin(8t))")
plt.xlabel("x = sin(10t)")
plt.ylabel("y = sin(8t)")
plt.axhline(0, color='black', linewidth=0.5, linestyle='--')
plt.axvline(0, color='black', linewidth=0.5, linestyle='--')
plt.grid(True)
plt.legend()
plt.show()
```



```
import numpy as np
import matplotlib.pyplot as plt

# 定数を設定
v = 10  # 初速度 (例: 10 m/s)
g = 9.8  # 重力加速度 (例: 9.8 m/s^2)
beta = np.radians(30)  # 角度 β (例: 30度をラジアンに変換)

# α の範囲を設定 (0度から90度)
alpha_degrees = np.linspace(0, 90, 500)
alpha = np.radians(alpha_degrees)  # 度をラジアンに変換

# 式を計算
numerator = 2 * v**2 * np.cos(alpha)**2 * (np.tan(alpha) + np.tan(beta))
denominator = g * np.cos(beta)
result = numerator / denominator

# プロット
plt.figure(figsize=(8, 6))
plt.plot(alpha_degrees, result, label=r"$\frac{2v^2 \cos^2\alpha (\tan\alpha + \tan\beta)}{g \cos\beta}$", color="blue")
plt.title("Horizontal Range as a Function of $\\alpha$")
plt.xlabel(r"$\alpha$ (degrees)")
plt.ylabel("Result")
plt.axhline(0, color="black", linewidth=0.8, linestyle="--")
plt.grid()
plt.legend()
plt.show()
```


```

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import pearsonr
from sympy import symbols, solve, Eq

# 1. 数と集合 (簡単な無理数の計算, 集合と命題)
def calculate_irrational():
    # 無理数の例: √2 の計算
    print(f"√2 = {np.sqrt(2)}")
    
def set_operations():
    # 集合の例
    A = {1, 2, 3}
    B = {2, 3, 4}
    print(f"A ∪ B = {A.union(B)}")
    print(f"A ∩ B = {A.intersection(B)}")

# 2. 式の展開と因数分解
def expand_and_factorize():
    x = symbols('x')
    expression = (x + 2) * (x - 3)
    expanded = expression.expand()
    factored = expanded.factor()
    print(f"展開: {expanded}")
    print(f"因数分解: {factored}")

# 3. 一次不等式の解
def solve_linear_inequality():
    x = symbols('x')
    inequality = Eq(2 * x + 3, 7)
    solution = solve(inequality, x)
    print(f"一次方程式の解: x = {solution}")

# 4. 三角比 (鋭角, 鈍角, 正弦定理, 余弦定理)
def triangle_properties():
    angle = np.radians(45)  # 角度 45 度
    sin_val = np.sin(angle)
    cos_val = np.cos(angle)
    print(f"sin(45°) = {sin_val}")
    print(f"cos(45°) = {cos_val}")

# 5. 二次関数の最大・最小とグラフ
def quadratic_function():
    x = np.linspace(-10, 10, 1000)
    y = x**2 - 4 * x + 5
    plt.figure()
    plt.plot(x, y, label='y = x^2 - 4x + 5')
    plt.title("Quadratic Function")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.grid()
    plt.legend()
    plt.show()

# 6. データの分析 (データの散らばり, 分散, 相関係数)
def analyze_data():
    data_x = [1, 2, 3, 4, 5]
    data_y = [2, 4, 6, 8, 10]
    variance = np.var(data_y)
    std_dev = np.std(data_y)
    correlation, _ = pearsonr(data_x, data_y)
    print(f"分散: {variance}")
    print(f"標準偏差: {std_dev}")
    print(f"相関係数: {correlation}")

# 7. 散布図
    plt.scatter(data_x, data_y, color='blue')
    plt.title("Scatter Plot")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.grid()
    plt.show()

# 実行
if __name__ == "__main__":
    print("# 1. 数と集合")
    calculate_irrational()
    set_operations()

    print("\n# 2. 式の展開と因数分解")
    expand_and_factorize()

    print("\n# 3. 一次不等式の解")
    solve_linear_inequality()

    print("\n# 4. 三角比")
    triangle_properties()

    print("\n# 5. 二次関数")
    quadratic_function()

    print("\n# 6. データの分析")
    analyze_data()
```

```
import numpy as np
import matplotlib.pyplot as plt
from sympy import symbols, Eq, solve, diff, integrate, pi, cos, sin, exp, log

# 1. 多項式の乗法・除法、分数式
def polynomial_operations():
    x = symbols('x')
    poly1 = x**2 + 2*x + 1
    poly2 = x + 1
    product = poly1 * poly2
    division = poly1 / poly2
    print(f"多項式の乗法: {product}")
    print(f"多項式の除法: {division}")
    
    # プロット
    x_vals = np.linspace(-10, 10, 400)
    poly1_func = np.vectorize(lambda x_val: poly1.subs(x, x_val))
    poly2_func = np.vectorize(lambda x_val: poly2.subs(x, x_val))
    plt.figure()
    plt.plot(x_vals, poly1_func(x_vals), label='poly1', color='blue')
    plt.plot(x_vals, poly2_func(x_vals), label='poly2', color='orange')
    plt.title("Polynomial Functions")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.legend()
    plt.grid()
    plt.show()

# 2. 二項定理
def binomial_theorem():
    n, x, y = symbols('n x y')
    binomial = (x + y)**3  # Example for n=3
    expanded = binomial.expand()
    print(f"二項定理展開: {expanded}")

# 3. 等式と不等式の証明
def equality_proof():
    x = symbols('x')
    eq = Eq(2*x + 3, 7)
    solution = solve(eq, x)
    print(f"等式の解: x = {solution}")

# 4. 高次方程式
def solve_high_order_equation():
    x = symbols('x')
    eq = Eq(x**3 - 6*x**2 + 11*x - 6, 0)
    solutions = solve(eq, x)
    print(f"高次方程式の解: {solutions}")

    # プロット
    x_vals = np.linspace(0, 4, 400)
    func = lambda x_val: x_val**3 - 6*x_val**2 + 11*x_val - 6
    y_vals = func(x_vals)
    plt.figure()
    plt.plot(x_vals, y_vals, label='x^3 - 6x^2 + 11x - 6', color='green')
    plt.axhline(0, color='black', linewidth=0.8, linestyle='--')
    plt.title("Cubic Function")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.grid()
    plt.legend()
    plt.show()

# 5. 直線と円
def line_and_circle():
    x, y = symbols('x y')
    line_eq = Eq(2*x + y - 4, 0)
    circle_eq = Eq(x**2 + y**2 - 4, 0)
    intersection = solve([line_eq, circle_eq], (x, y))
    print(f"直線と円の交点: {intersection}")

    # プロット
    theta = np.linspace(0, 2 * np.pi, 500)
    circle_x = 2 * np.cos(theta)
    circle_y = 2 * np.sin(theta)
    line_x = np.linspace(-2, 2, 500)
    line_y = 4 - 2 * line_x
    plt.figure()
    plt.plot(circle_x, circle_y, label='Circle: x^2 + y^2 = 4', color='blue')
    plt.plot(line_x, line_y, label='Line: 2x + y = 4', color='red')
    plt.scatter(*zip(*[(float(pt[0]), float(pt[1])) for pt in intersection]), color='black', zorder=5)
    plt.axhline(0, color='black', linewidth=0.8, linestyle='--')
    plt.axvline(0, color='black', linewidth=0.8, linestyle='--')
    plt.legend()
    plt.grid()
    plt.xlabel("x")
    plt.ylabel("y")
    plt.title("Intersection of Line and Circle")
    plt.show()

# 6. 指数関数と対数関数
def exponential_and_logarithmic():
    x = symbols('x')
    exp_func = exp(x)
    log_func = log(x)
    print(f"指数関数: e^x = {exp_func}")
    print(f"対数関数: log(x) = {log_func}")

    # プロット
    x_vals = np.linspace(0.1, 5, 400)
    exp_vals = np.exp(x_vals)
    log_vals = np.log(x_vals)
    plt.figure()
    plt.plot(x_vals, exp_vals, label='e^x', color='purple')
    plt.plot(x_vals, log_vals, label='log(x)', color='orange')
    plt.axhline(0, color='black', linewidth=0.8, linestyle='--')
    plt.axvline(0, color='black', linewidth=0.8, linestyle='--')
    plt.legend()
    plt.title("Exponential and Logarithmic Functions")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.grid()
    plt.show()

# 7. 三角関数の加法定理と2倍角の公式
def trigonometric_properties():
    angle = np.linspace(0, 2 * np.pi, 500)
    cos_vals = np.cos(angle)
    sin_vals = np.sin(angle)
    plt.figure()
    plt.plot(angle, cos_vals, label='cos(x)', color='blue')
    plt.plot(angle, sin_vals, label='sin(x)', color='red')
    plt.axhline(0, color='black', linewidth=0.8, linestyle='--')
    plt.axvline(0, color='black', linewidth=0.8, linestyle='--')
    plt.title("Trigonometric Functions")
    plt.xlabel("Angle (radians)")
    plt.ylabel("Value")
    plt.legend()
    plt.grid()
    plt.show()

# 8. 微分と積分
def differentiation_and_integration():
    x = symbols('x')
    func = x**3 - 3*x**2 + 2*x
    derivative = diff(func, x)
    integral = integrate(func, x)
    print(f"微分: {derivative}")
    print(f"積分: {integral}")

    # プロット
    x_vals = np.linspace(-1, 3, 400)
    func_vals = [func.subs(x, val) for val in x_vals]
    derivative_vals = [derivative.subs(x, val) for val in x_vals]
    plt.figure()
    plt.plot(x_vals, func_vals, label='Original Function', color='blue')
    plt.plot(x_vals, derivative_vals, label='Derivative', color='red', linestyle='--')
    plt.axhline(0, color='black', linewidth=0.8, linestyle='--')
    plt.title("Function and Derivative")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.legend()
    plt.grid()
    plt.show()

# 9. 面積計算
def area_under_curve():
    x = symbols('x')
    curve = x**2
    area = integrate(curve, (x, 0, 2))  # Example: From x=0 to x=2
    print(f"面積: {area}")

    # プロット
    x_vals = np.linspace(0, 2, 400)
    y_vals = x_vals**2
    plt.figure()
    plt.plot(x_vals, y_vals, label='$y = x^2$', color='blue')
    plt.fill_between(x_vals, y_vals, color='blue', alpha=0.2)
    plt.title("Area Under Curve")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.grid()
    plt.legend()
    plt.show()

# 実行
if __name__ == "__main__":
    print("# 1. 多項式の乗法・除法、分数式")
    polynomial_operations()

    print("\n# 2. 二項定理")
    binomial_theorem()

    print("\n# 3. 等式と不等式の証明")
    equality_proof()

    print("\n# 4. 高次方程式")
    solve_high_order_equation()

    print("\n# 5. 直線と円")
    line_and_circle()

    print("\n# 6. 指数関数と対数関数")
    exponential_and_logarithmic()

    print("\n# 7. 三角関数の加法定理と2倍角の公式")
    trigonometric_properties()

    print("\n# 8. 微分と積分")
    differentiation_and_integration()

    print("\n# 9. 面積計算")
    area_under_curve()

```


```
import numpy as np
import matplotlib.pyplot as plt
from sympy import symbols, Eq, solve, diff, integrate, limit, pi, cos, sin, exp, log

# 1. 極限と数列
# 数列の極限
# 無限等比級数の和

def sequence_limits():
    n, r = symbols('n r')
    geometric_sequence = r**n
    limit_value = limit(geometric_sequence, n, np.inf)
    print(f"数列 {geometric_sequence} の極限: {limit_value}")

    # 無限等比級数の和
    a = symbols('a')
    sum_infinite = a / (1 - r)  # |r| < 1 の場合
    print(f"無限等比級数の和: {sum_infinite}")

# 2. 分数関数と無理関数

def fractional_and_irrational_functions():
    x = symbols('x')
    fractional_func = 1 / (x + 1)
    irrational_func = (x + 1)**0.5

    print(f"分数関数: {fractional_func}")
    print(f"無理関数: {irrational_func}")

    # プロット
    x_vals = np.linspace(-0.9, 5, 400)
    fractional_vals = 1 / (x_vals + 1)
    irrational_vals = np.sqrt(x_vals + 1)

    plt.figure(figsize=(10, 6))
    plt.plot(x_vals, fractional_vals, label='Fractional Function 1/(x+1)', color='blue')
    plt.plot(x_vals, irrational_vals, label='Irrational Function sqrt(x+1)', color='green')
    plt.axhline(0, color='black', linewidth=0.8, linestyle='--')
    plt.axvline(0, color='black', linewidth=0.8, linestyle='--')
    plt.title("Fractional and Irrational Functions")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.legend()
    plt.grid()
    plt.show()

# 3. 合成関数と逆関数

def composite_and_inverse_functions():
    x = symbols('x')
    f = 2*x + 3
    g = (x - 3) / 2  # 逆関数

    composite = f.subs(x, g)
    print(f"合成関数 f(g(x)): {composite}")
    print(f"逆関数 g(x): {g}")

# 4. 微分と積分

def differentiation_and_integration():
    x = symbols('x')
    func = x**3 - 3*x**2 + 2*x

    # 微分
    derivative = diff(func, x)
    print(f"導関数: {derivative}")

    # 積分
    integral = integrate(func, x)
    print(f"不定積分: {integral}")

    # プロット
    x_vals = np.linspace(-1, 3, 400)
    func_vals = [func.subs(x, val) for val in x_vals]
    derivative_vals = [derivative.subs(x, val) for val in x_vals]

    plt.figure(figsize=(10, 6))
    plt.plot(x_vals, func_vals, label='Original Function', color='blue')
    plt.plot(x_vals, derivative_vals, label='Derivative', color='red', linestyle='--')
    plt.axhline(0, color='black', linewidth=0.8, linestyle='--')
    plt.title("Function and Derivative")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.legend()
    plt.grid()
    plt.show()

# 5. 積分の応用
# 面積、体積、曲線の長さ

def integration_applications():
    x = symbols('x')
    curve = x**2

    # 面積
    area = integrate(curve, (x, 0, 2))
    print(f"面積: {area}")

    # プロット
    x_vals = np.linspace(0, 2, 400)
    y_vals = x_vals**2
    plt.figure(figsize=(10, 6))
    plt.plot(x_vals, y_vals, label='$y = x^2$', color='blue')
    plt.fill_between(x_vals, y_vals, color='blue', alpha=0.2)
    plt.title("Area Under Curve")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.grid()
    plt.legend()
    plt.show()

# 実行
if __name__ == "__main__":
    print("# 1. 極限と数列")
    sequence_limits()

    print("\n# 2. 分数関数と無理関数")
    fractional_and_irrational_functions()

    print("\n# 3. 合成関数と逆関数")
    composite_and_inverse_functions()

    print("\n# 4. 微分と積分")
    differentiation_and_integration()

    print("\n# 5. 積分の応用")
    integration_applications()

```


```
import numpy as np
import matplotlib.pyplot as plt
from sympy import symbols, Eq, solve, diff, integrate, limit, pi, cos, sin, exp, log, factorial

# 1. 図形の性質
# 平面図形: 三角形の性質、円の性質、作図

def geometric_properties():
    x, y = symbols('x y')
    triangle_base = 5
    triangle_height = 3
    circle_radius = 4

    # 三角形の面積
    triangle_area = (triangle_base * triangle_height) / 2
    print(f"三角形の面積: {triangle_area}")

    # 円の面積
    circle_area = pi * circle_radius**2
    print(f"円の面積: {circle_area}")

    # 作図（例: 円と三角形のプロット）
    theta = np.linspace(0, 2 * np.pi, 500)
    circle_x = circle_radius * np.cos(theta)
    circle_y = circle_radius * np.sin(theta)

    plt.figure(figsize=(8, 8))
    plt.plot(circle_x, circle_y, label='Circle', color='blue')
    plt.fill([0, triangle_base, 0], [0, 0, triangle_height], color='orange', alpha=0.5, label='Triangle')
    plt.axhline(0, color='black', linewidth=0.8, linestyle='--')
    plt.axvline(0, color='black', linewidth=0.8, linestyle='--')
    plt.title("Geometric Properties")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.legend()
    plt.grid()
    plt.axis('equal')
    plt.show()

# 2. 場合の数と確率
# 場合の数、順列・組合せ、確率

def combinations_and_probability():
    n, r = symbols('n r')

    # 順列
    permutation = factorial(n) / factorial(n - r)
    print(f"順列 P(n, r): {permutation}")

    # 組合せ
    combination = factorial(n) / (factorial(r) * factorial(n - r))
    print(f"組合せ C(n, r): {combination}")

    # 確率計算例
    total_outcomes = 6
    favorable_outcomes = 2
    probability = favorable_outcomes / total_outcomes
    print(f"確率: {probability}")

# 3. 数学と人間の活動
# ユークリッドの互除法、二進法、平面や空間における点の位置

def math_and_human_activity():
    # ユークリッドの互除法
    a, b = 56, 98
    while b:
        a, b = b, a % b
    gcd = a
    print(f"ユークリッドの互除法による最大公約数: {gcd}")

    # 二進法
    number = 19
    binary_representation = bin(number)[2:]
    print(f"数 {number} の二進法表記: {binary_representation}")

    # 点の位置
    x, y = symbols('x y')
    point = (3, 4)
    distance_from_origin = (point[0]**2 + point[1]**2)**0.5
    print(f"原点から点 {point} までの距離: {distance_from_origin}")

    # プロット
    plt.figure(figsize=(8, 8))
    plt.scatter([0, point[0]], [0, point[1]], color=['black', 'red'], label=['Origin', 'Point'])
    plt.plot([0, point[0]], [0, point[1]], color='red', linestyle='--', label='Distance')
    plt.axhline(0, color='black', linewidth=0.8, linestyle='--')
    plt.axvline(0, color='black', linewidth=0.8, linestyle='--')
    plt.title("Point and Distance")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.legend()
    plt.grid()
    plt.axis('equal')
    plt.show()

# 実行
if __name__ == "__main__":
    print("# 1. 図形の性質")
    geometric_properties()

    print("\n# 2. 場合の数と確率")
    combinations_and_probability()

    print("\n# 3. 数学と人間の活動")
    math_and_human_activity()

```

```
import numpy as np
import matplotlib.pyplot as plt
from sympy import symbols, Eq, solve, diff, integrate, limit, pi, cos, sin, exp, log, factorial, S

# 1. 図形の性質
# 平面図形: 三角形の性質、円の性質、作図

def geometric_properties():
    x, y = symbols('x y')
    triangle_base = 5
    triangle_height = 3
    circle_radius = 4

    # 三角形の面積
    triangle_area = (triangle_base * triangle_height) / 2
    print(f"三角形の面積: {triangle_area}")

    # 円の面積
    circle_area = pi * circle_radius**2
    print(f"円の面積: {circle_area}")

    # 作図（例: 円と三角形のプロット）
    theta = np.linspace(0, 2 * np.pi, 500)
    circle_x = circle_radius * np.cos(theta)
    circle_y = circle_radius * np.sin(theta)

    plt.figure(figsize=(8, 8))
    plt.plot(circle_x, circle_y, label='Circle', color='blue')
    plt.fill([0, triangle_base, 0], [0, 0, triangle_height], color='orange', alpha=0.5, label='Triangle')
    plt.axhline(0, color='black', linewidth=0.8, linestyle='--')
    plt.axvline(0, color='black', linewidth=0.8, linestyle='--')
    plt.title("Geometric Properties")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.legend()
    plt.grid()
    plt.axis('equal')
    plt.show()

# 2. 場合の数と確率
# 場合の数、順列・組合せ、確率

def combinations_and_probability():
    n, r = symbols('n r')

    # 順列
    permutation = factorial(n) / factorial(n - r)
    print(f"順列 P(n, r): {permutation}")

    # 組合せ
    combination = factorial(n) / (factorial(r) * factorial(n - r))
    print(f"組合せ C(n, r): {combination}")

    # 確率計算例
    total_outcomes = 6
    favorable_outcomes = 2
    probability = favorable_outcomes / total_outcomes
    print(f"確率: {probability}")

# 3. 数列とその和
# 等差数列と等比数列、漸化式、数学的帰納法

def sequences_and_series():
    # 等差数列
    a1, d, n = symbols('a1 d n', real=True)
    arithmetic_nth = a1 + (n - 1) * d
    arithmetic_sum = n / 2 * (2 * a1 + (n - 1) * d)
    print(f"等差数列: 第n項 = {arithmetic_nth}, 和 = {arithmetic_sum}")

    # 等比数列
    a, r = symbols('a r', real=True)
    geometric_nth = a * r**(n - 1)
    geometric_sum = a * (1 - r**n) / (1 - r)
    print(f"等比数列: 第n項 = {geometric_nth}, 和 = {geometric_sum}")

    # 漸化式と数学的帰納法（例: フィボナッチ数列）
    fib_seq = [0, 1]
    for i in range(2, 10):
        fib_seq.append(fib_seq[-1] + fib_seq[-2])
    print(f"フィボナッチ数列: {fib_seq}")

# 4. 確率分布と統計的な推測
# 二項分布、正規分布、区間推定、仮説検定

def probability_and_statistics():
    x, n, p = symbols('x n p', real=True)

    # 二項分布
    binomial_prob = factorial(n) / (factorial(x) * factorial(n - x)) * p**x * (1 - p)**(n - x)
    print(f"二項分布の確率: {binomial_prob}")

    # 正規分布
    mu, sigma = symbols('mu sigma', real=True)
    normal_dist = (1 / (sigma * (2 * pi)**0.5)) * exp(-0.5 * ((x - mu) / sigma)**2)
    print(f"正規分布: {normal_dist}")

    # 区間推定と仮説検定（例示）
    sample_mean, sample_std, sample_size = 50, 10, 30
    margin_of_error = 1.96 * (sample_std / sample_size**0.5)
    confidence_interval = (sample_mean - margin_of_error, sample_mean + margin_of_error)
    print(f"95%信頼区間: {confidence_interval}")

# 実行
if __name__ == "__main__":
    print("# 1. 図形の性質")
    geometric_properties()

    print("\n# 2. 場合の数と確率")
    combinations_and_probability()

    print("\n# 3. 数列とその和")
    sequences_and_series()

    print("\n# 4. 確率分布と統計的な推測")
    probability_and_statistics()

```


```
import numpy as np
import matplotlib.pyplot as plt

# -------------------------------
# ベクトル演算
# -------------------------------
v1 = np.array([3, 4])
v2 = np.array([1, 2])
dot_product = np.dot(v1, v2)  # ベクトルの内積
print(f"Vector 1: {v1}, Vector 2: {v2}, Dot Product: {dot_product}")

# -------------------------------
# 空間座標とベクトル
# -------------------------------
v3 = np.array([1, 1, 1])
v4 = np.array([2, 3, 4])
cross_product = np.cross(v3, v4)  # 外積
print(f"Vector 3: {v3}, Vector 4: {v4}, Cross Product: {cross_product}")

# -------------------------------
# 平面上の曲線と複素数平面
# -------------------------------
t = np.linspace(0, 2 * np.pi, 500)
x = np.sin(2 * t)
y = np.cos(3 * t)

plt.figure(figsize=(8, 6))
plt.plot(x, y, label="Curve (Lissajous)", color='blue')
plt.title("Lissajous Curve")
plt.xlabel("x")
plt.ylabel("y")
plt.grid()
plt.legend()
plt.show()

# -------------------------------
# 複素数平面とド・モアブルの定理
# -------------------------------
theta = np.linspace(0, 2 * np.pi, 100)
complex_circle = np.exp(1j * theta)  # ド・モアブルの定理を使用
plt.figure(figsize=(6, 6))
plt.plot(complex_circle.real, complex_circle.imag, label="Unit Circle", color='green')
plt.axhline(0, color='black', linestyle='--', linewidth=0.5)
plt.axvline(0, color='black', linestyle='--', linewidth=0.5)
plt.title("Complex Plane: Unit Circle")
plt.xlabel("Real Part")
plt.ylabel("Imaginary Part")
plt.grid()
plt.legend()
plt.show()

# -------------------------------
# 行列の演算
# -------------------------------
A = np.array([[2, 1], [1, 3]])
B = np.array([[1, 0], [0, 1]])
matrix_product = np.dot(A, B)
print(f"Matrix A:\n{A}\nMatrix B:\n{B}\nProduct:\n{matrix_product}")

# -------------------------------
# 統計グラフ: ヒストグラム
# -------------------------------
data = np.random.normal(0, 1, 1000)  # 平均0, 標準偏差1の正規分布
plt.figure(figsize=(8, 6))
plt.hist(data, bins=30, color='purple', alpha=0.7, label="Histogram of Data")
plt.title("Histogram of Random Data")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.grid()
plt.legend()
plt.show()


```
https://ja.wolframalpha.com/input?i=sin%5E2%28x%29+%2B+2+sin%5E4%282x%29%E3%82%920%E3%81%8B%E3%82%89%CF%80%E3%81%BE%E3%81%A7%E7%A9%8D%E5%88%86%E3%81%99%E3%82%8B


```

import numpy as np
from scipy.integrate import quad

# 積分する関数の定義
def integrand(x):
    return np.sin(x)**2 + 2 * np.sin(2*x)**4

# 積分範囲
a = 0
b = np.pi

# 数値積分の実行
result, error = quad(integrand, a, b)

# 結果の表示
print("積分結果:", result)
print("誤差:", error)

import sympy as sp

# シンボリック変数の定義
x = sp.symbols('x')

# 積分する関数の定義
integrand = sp.sin(x)**2 + 2 * sp.sin(2*x)**4

# 積分を実行
result_symbolic = sp.integrate(integrand, (x, 0, sp.pi))

# 結果の表示
result_symbolic

```
https://ja.wolframalpha.com/input?i=-2%3C%3Dx%3C%3D2%2C-2%3C%3Dy%3C%3D2%E3%81%AE%E3%81%A8%E3%81%8Dx%5E2+y%5E2+%2B+x+y%5E3%E3%81%AE%E7%A9%8D%E5%88%86




```
# シンボリック変数の定義
x, y = sp.symbols('x y')

# 積分する関数の定義
integrand_2d = x**2 * y**2 + x * y**3

# 2重積分を実行 (-2 <= x <= 2, -2 <= y <= 2)
result_2d = sp.integrate(integrand_2d, (x, -2, 2), (y, -2, 2))

# 結果の表示
result_2d




```

```



```