Determine determinant-2
Determine determinant-2
return [
[matrix[i][j] for j in range(len(matrix)) if j != col]
for i in range(len(matrix)) if i != row
]
def calculate_determinant(matrix):
"""Recursive function to calculate determinant using loops."""
n = len(matrix)
if n == 1:
return matrix[0][0]
if n == 2:
# Base case for 2x2 matrix
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
return calculate_determinant(matrix)
# Example usage
# matrix = [
# [2, 3, 1],
# [4, 5, 6],
# [7, 8, 9]
# ]
1
matrix = np.array([[i+j/3 for i in range(4)] for j in range(4)])
matrix = np.array([
[1, 2, 3, 44, 5],
[5, 66, 7, 8, 34],
[9, 10, 1.4, 12, 67],
[13, 14, 15, 16, 7],
[13, 14, 1.5, 16, -12]
])
def f(x):
"""Define the function f(x)= x - tan(x)."""
return x - math.tan(x)
Args:
func: The function for which we are finding a root.
a, b: The endpoints of the interval.
tol: The tolerance for convergence.
max_iter: Maximum number of iterations.
Returns:
The approximate root, or None if no sign change is detected.
"""
fa = func(a)
fb = func(b)
if fa * fb > 0:
# No sign change in [a,b] so bisection cannot be applied
return None
for _ in range(max_iter):
mid = (a + b) / 2.0
2
fmid = func(mid)
if abs(fmid) < tol:
return mid
# Decide which subinterval contains the root.
if fa * fmid < 0:
b = mid
fb = fmid
else:
a = mid
fa = fmid
return (a + b) / 2.0
3
for (a, b) in intervals:
try:
fa = f(a)
fb = f(b)
except Exception as e:
continue # Skip if function evaluation fails
if fa * fb < 0:
root = bisection(f, a, b)
if root is not None:
roots.append(root)
else:
if abs(fa) < 1e-6:
roots.append(a)
if abs(fb) < 1e-6:
roots.append(b)
def f(x):
"""Define the function f(x)= x - tan(x)."""
return x - math.tan(x)
4
if point >= 20:
break
discont.append(point)
k += 1
if discont:
intervals.append((discont[-1] + delta, 20))
roots = []
# In each continuous subinterval, use brentq if a sign change is detected.
for a, b in intervals:
try:
fa, fb = f(a), f(b)
except Exception:
continue
if fa * fb < 0:
try:
root = brentq(f, a, b, xtol=1e-6)
roots.append(root)
except Exception as e:
print(f"Error finding root in interval [{a}, {b}]:", e)
5
17.22075551122087
def f(x):
return x - math.tan(x)
[[0. 1. 2. 3. ]
6
[0.33333333 1.33333333 2.33333333 3.33333333]
[0.66666667 1.66666667 2.66666667 3.66666667]
[1. 2. 3. 4. ]]
[9]: # Gpt
import numpy as np
import matplotlib.pyplot as plt
def transform_x(T):
"""
Transform temperature T (in °C) to a new x-coordinate:
- For T <= 100: linear mapping so that -100->0 and 100->200.
- For T > 100: compress range [100,1000] to span 200 units.
"""
T = np.array(T)
newX = np.where(T <= 100, T + 100, 200 + (2/9)*(T - 100))
return newX
def transform_y(h):
"""
Transform height h (in km) to a new y-coordinate:
- For h <= 100: identity.
- For h > 100: compress range [100,1000] to span 100 units.
"""
h = np.array(h)
newY = np.where(h <= 100, h, 100 + (h - 100)/9)
return newY
7
T_thermo = -90 + (1500 - (-90))/(600 - 85) * (h_thermo - 85)
T_strat_t = transform_x(T_strat)
h_strat_t = transform_y(h_strat)
T_meso_t = transform_x(T_meso)
h_meso_t = transform_y(h_meso)
T_thermo_t = transform_x(T_thermo)
h_thermo_t = transform_y(h_thermo)
8
plt.annotate("Thermopause\n(600 km, 1500°C)",
xy=(transform_x(1500), transform_y(600)),
xytext=(transform_x(1500)-80, transform_y(600)-10),
arrowprops=dict(facecolor='black', shrink=0.05), fontsize=10)
height_ticks = np.array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 500, 1000])
plt.xticks(temp_tick_pos, temp_ticks)
plt.yticks(height_tick_pos, height_ticks)
plt.legend(fontsize=10)
plt.grid(True)
plt.show()
9
[77]: %config InlineBackend.figure_format = 'retina'
import numpy as np
import matplotlib.pyplot as plt
# Transformation functions
def transform_height(h):
return np.where(h <= 100, h, 100 + (h - 100) / 9)
def transform_temperature(T):
return np.where(T <= 100, T, 100 + (T - 100) / 9)
# Stratosphere: 11 to 50 km
h_strato1 = np.linspace(11, 20, 50) # Lower part, isothermal
T_strato1 = -56.5 * np.ones_like(h_strato1)
h_strato2 = np.linspace(20, 50, 100) # Upper part, increasing
T_strato2 = -56.5 + (0 - (-56.5)) / (50 - 20) * (h_strato2 - 20)
10
# Mesosphere: 50 to 85 km
h_meso = np.linspace(50, 85, 100)
T_meso = 0 - (90 / (85 - 50)) * (h_meso - 50)
# Thermosphere: 85 to 1000 km
h_thermo = np.linspace(85, 1000, 200)
T_thermo = -90 + (1000 - (-90)) / (1000 - 85) * (h_thermo - 85)
# Transform data
h_plot_tropo = transform_height(h_tropo)
T_plot_tropo = transform_temperature(T_tropo)
h_plot_strato1 = transform_height(h_strato1)
T_plot_strato1 = transform_temperature(T_strato1)
h_plot_strato2 = transform_height(h_strato2)
T_plot_strato2 = transform_temperature(T_strato2)
h_plot_meso = transform_height(h_meso)
T_plot_meso = transform_temperature(T_meso)
h_plot_thermo = transform_height(h_thermo)
T_plot_thermo = transform_temperature(T_thermo)
# Create plot
plt.figure(figsize=(10, 8))
plt.plot(T_plot_tropo, h_plot_tropo, 'b', linewidth=2, label='Troposphere')
plt.plot(T_plot_strato1, h_plot_strato1, 'g', linewidth=2)
plt.plot(T_plot_strato2, h_plot_strato2, 'g', linewidth=2, label='Stratosphere')
plt.plot(T_plot_meso, h_plot_meso, 'r', linewidth=2, label='Mesosphere')
plt.plot(T_plot_thermo, h_plot_thermo, 'm', linewidth=2, label='Thermosphere')
# Custom ticks
h_tick = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 500, 1000]
T_tick = [-100, -80, -60, -40, -20, 0, 20, 40, 60, 80, 100, 500, 1000]
h_plot_tick = [transform_height(h) for h in h_tick]
T_plot_tick = [transform_temperature(T) for T in T_tick]
plt.yticks(h_plot_tick, labels=[str(h) for h in h_tick])
plt.xticks(T_plot_tick, labels=[str(T) for T in T_tick])
# Set limits
plt.ylim(0, 200)
plt.xlim(-100, 200)
# Grid
plt.grid(True, linestyle='--', alpha=0.5)
11
# Label layers
plt.annotate('Troposphere',
xy=(transform_temperature(10), transform_height(5)),
xytext=(0, 10),
arrowprops=None,
fontsize=12,
color='b',
ha='left')
plt.annotate('Stratosphere',
xy=(transform_temperature(-20), transform_height(30)),
xytext=(-20, 30),
arrowprops=None,
fontsize=12,
color='g',
ha='left')
plt.annotate('Mesosphere',
xy=(transform_temperature(-30), transform_height(70)),
xytext=(-80, 60),
arrowprops=None,
fontsize=12,
color='r',
ha='left')
plt.annotate('Thermosphere',
xy=(transform_temperature(500), transform_height(500)),
xytext=(40, 120),
arrowprops=None,
fontsize=12,
color='m',
ha='left')
# Mark boundaries
plt.annotate('Stratopause\n(0°C, 50 km)',
xy=(transform_temperature(0), transform_height(50)),
xytext=(10, 47),
fontsize=10)
12
plt.plot(transform_temperature(-90), transform_height(85), 'ko', markersize=8) ␣
↪# Mesopause
plt.annotate('Mesopause\n(-90°C, 85 km)',
xy=(transform_temperature(-90), transform_height(85)),
xytext=(-73, 82),
fontsize=10)
# Show plot
plt.savefig("high_res_plot.png", dpi=3000)
plt.show()
[14]: # deepseek
import numpy as np
import matplotlib.pyplot as plt
13
transformed = np.where(h <= 100, h, 100 + (h - 100)/9)
return transformed
def transform_temp(t):
t = np.asarray(t)
transformed = np.where(t <= 100, t, 100 + (t - 100)*(200/900))
return transformed
heights_transformed = transform_height(heights)
temps_transformed = transform_temp(temps)
# Create plot
plt.figure(figsize=(12, 10))
plt.plot(temps_transformed, heights_transformed, color='blue')
x_ticks = [-100,-80,-60,-40,-20,0,20,40,60,80,100,500,1000]
plt.xticks(transform_temp(x_ticks), labels=[str(x) for x in x_ticks])
plt.xlabel('Temperature (°C)', fontsize=12)
14
# Add grid and title
plt.grid(True, linestyle='--', alpha=0.7)
plt.title('Earth Atmosphere Temperature Profile with Compressed Axes',␣
↪fontsize=14, pad=20)
ha='right', va='bottom')
ha='right', va='bottom')
plt.tight_layout()
plt.show()
15
[74]: %config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
import numpy as np
plt.plot(x, y)
plt.xlabel("x")
plt.ylabel("cos(x)")
plt.title("High-Resolution Inline Plot")
plt.show()
16
[ ]:
17