0% found this document useful (0 votes)
7 views

Determine determinant-2

The document provides Python code for calculating the determinant of matrices using both a custom recursive function and NumPy's built-in functionality. It also includes a method for finding roots of the function f(x) = x - tan(x) using the bisection method and Brent's method, while avoiding discontinuities. Additionally, it presents a visualization of Earth's atmospheric temperature profile using transformed coordinates.

Uploaded by

Sougata Halder
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Determine determinant-2

The document provides Python code for calculating the determinant of matrices using both a custom recursive function and NumPy's built-in functionality. It also includes a method for finding roots of the function f(x) = x - tan(x) using the bisection method and Brent's method, while avoiding discontinuities. Additionally, it presents a visualization of Earth's atmospheric temperature profile using transformed coordinates.

Uploaded by

Sougata Halder
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Determine determinant

March 30, 2025

[8]: def determinant(matrix):


def minor(matrix, row, col):
"""Return the minor of the matrix by excluding the specified row and␣
↪column."""

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]

# General case for nxn matrix


det = 0
for col in range(n):
cofactor = matrix[0][col] * calculate_determinant(minor(matrix, 0,␣
↪col))
det += cofactor if col % 2 == 0 else -cofactor
return det

return calculate_determinant(matrix)

# Example usage
# matrix = [
# [2, 3, 1],
# [4, 5, 6],
# [7, 8, 9]
# ]

# print("Determinant of the matrix is:", determinant(matrix))

1
matrix = np.array([[i+j/3 for i in range(4)] for j in range(4)])

print("Determinant of the matrix is:", determinant(matrix))

Determinant of the matrix is: -1.1102230246251565e-16

[2]: import numpy as np

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]
])

# Calculate the determinant using NumPy


det = np.linalg.det(matrix)

print("Determinant of the matrix is:", det)

Determinant of the matrix is: -33927551.99999995

[1]: import math

def f(x):
"""Define the function f(x)= x - tan(x)."""
return x - math.tan(x)

def bisection(func, a, b, tol=1e-6, max_iter=100):


"""Bisection method to find a root of func in [a, b].

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

# Create a list of discontinuity points for tan(x) in [0,20]


# tan(x) has vertical asymptotes at x = pi/2 + k*pi.
discont = []
k = 0
while True:
point = math.pi/2 + k*math.pi
if point >= 20:
break
discont.append(point)
k += 1

# Use a small offset to avoid evaluating exactly at the asymptotes


delta = 1e-5

# Define subintervals that avoid the discontinuities.


intervals = []

# First interval: from 0 to the first discontinuity - delta


if discont:
intervals.append((0, discont[0] - delta))
else:
intervals.append((0, 20))

# Intermediate intervals: between discontinuities.


for i in range(len(discont) - 1):
intervals.append((discont[i] + delta, discont[i+1] - delta))

# Last interval: from last discontinuity + delta to 20.


if discont:
intervals.append((discont[-1] + delta, 20))

# List to collect found roots.


roots = []

# Check each subinterval for a sign change and apply bisection.

3
for (a, b) in intervals:
try:
fa = f(a)
fb = f(b)
except Exception as e:
continue # Skip if function evaluation fails

# If there's a sign change or one endpoint is very close to zero, search␣


↪for a root.

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)

# Remove any duplicate roots (for instance, x = 0 might appear twice)


roots = sorted(set(roots))

print("Roots of f(x) = x - tan(x) in [0, 20]:")


for root in roots:
print(root)

Roots of f(x) = x - tan(x) in [0, 20]:


0
4.493409485517356
7.725251836482155
10.904121652458548
14.066193916962256
17.220755274317913

[2]: import math


from scipy.optimize import brentq

def f(x):
"""Define the function f(x)= x - tan(x)."""
return x - math.tan(x)

# Determine the discontinuities of tan(x) in [0,20]:


# tan(x) is undefined at x = pi/2 + k*pi.
discont = []
k = 0
while True:
point = math.pi/2 + k*math.pi

4
if point >= 20:
break
discont.append(point)
k += 1

# Use a small offset to avoid evaluating exactly at the asymptotes.


delta = 1e-5

# Split the interval [0,20] into continuous subintervals.


intervals = []
if discont:
intervals.append((0, discont[0] - delta))
else:
intervals.append((0, 20))

for i in range(len(discont) - 1):


intervals.append((discont[i] + delta, discont[i+1] - delta))

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)

# Remove duplicates and sort the list.


roots = sorted(set(roots))

print("Roots of f(x) = x - tan(x) in [0, 20]:")


for root in roots:
print(root)

Roots of f(x) = x - tan(x) in [0, 20]:


4.493409269636924
7.725251833449817
10.90412163625835
14.066193912872338

5
17.22075551122087

[3]: import math

def f(x):
return x - math.tan(x)

def bisection(f, a, b, tol=1e-6, max_iter=100):


if f(a) * f(b) >= 0:
return None # No root in the interval
for _ in range(max_iter):
c = (a + b) / 2
if abs(f(c)) < tol:
return c
if f(a) * f(c) < 0:
b = c
else:
a = c
return (a + b) / 2 # Return approximate root after max iterations

roots = [0.0] # Explicitly add the root at x=0

# Find roots in each interval (k*pi, (2k+1)*pi/2) for k from 1 to 5


for k in range(1, 6):
a = k * math.pi
b = (2 * k + 1) * math.pi / 2
root = bisection(f, a, b)
if root is not None:
roots.append(root)

# Sort the roots for better presentation


roots.sort()

print("Roots of f(x) = x - tan(x) in the interval [0, 20]:")


for root in roots:
print(f"{root:.6f}")

Roots of f(x) = x - tan(x) in the interval [0, 20]:


0.000000
4.493409
7.725252
10.904122
14.066194
17.220755

[7]: matrix = np.array([[i+j/3 for i in range(4)] for j in range(4)])


print (matrix)

[[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

# --- Transformation functions ---

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

# --- Define simplified atmospheric profiles ---

# Troposphere: 0 to 11 km, from 15°C to -56.5°C


h_trop = np.linspace(0, 11, 100)
T_trop = 15 + (-56.5 - 15)/11 * h_trop

# Stratosphere: 11 to 50 km, from -56.5°C to 0°C


h_strat = np.linspace(11, 50, 100)
T_strat = -56.5 + (0 - (-56.5))/(50 - 11) * (h_strat - 11)

# Mesosphere: 50 to 85 km, from 0°C to -90°C


h_meso = np.linspace(50, 85, 100)
T_meso = 0 + (-90 - 0)/(85 - 50) * (h_meso - 50)

# Thermosphere: 85 to 600 km, from -90°C to 1500°C


h_thermo = np.linspace(85, 600, 100)

7
T_thermo = -90 + (1500 - (-90))/(600 - 85) * (h_thermo - 85)

# --- Transform the data ---


T_trop_t = transform_x(T_trop)
h_trop_t = transform_y(h_trop)

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)

# --- Create the plot ---


plt.figure(figsize=(12,8))

plt.plot(T_trop_t, h_trop_t, label="Troposphere", color='blue', linewidth=2)


plt.plot(T_strat_t, h_strat_t, label="Stratosphere", color='green', linewidth=2)
plt.plot(T_meso_t, h_meso_t, label="Mesosphere", color='orange', linewidth=2)
plt.plot(T_thermo_t, h_thermo_t, label="Thermosphere", color='red', linewidth=2)

# --- Mark key boundaries ---


# Tropopause: ~11 km, -56.5°C
plt.plot(transform_x(-56.5), transform_y(11), 'ko')
plt.annotate("Tropopause\n(11 km, -56.5°C)",
xy=(transform_x(-56.5), transform_y(11)),
xytext=(transform_x(-56.5)-20, transform_y(11)+5),
arrowprops=dict(facecolor='black', shrink=0.05), fontsize=10)

# Stratopause: ~50 km, 0°C


plt.plot(transform_x(0), transform_y(50), 'ko')
plt.annotate("Stratopause\n(50 km, 0°C)",
xy=(transform_x(0), transform_y(50)),
xytext=(transform_x(0)+10, transform_y(50)+5),
arrowprops=dict(facecolor='black', shrink=0.05), fontsize=10)

# Mesopause: ~85 km, -90°C


plt.plot(transform_x(-90), transform_y(85), 'ko')
plt.annotate("Mesopause\n(85 km, -90°C)",
xy=(transform_x(-90), transform_y(85)),
xytext=(transform_x(-90)-30, transform_y(85)+5),
arrowprops=dict(facecolor='black', shrink=0.05), fontsize=10)

# Thermopause: ~600 km, 1500°C


plt.plot(transform_x(1500), transform_y(600), 'ko')

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)

# --- Set custom ticks ---


# Define original tick values for Temperature and Height:
temp_ticks = np.array([-100, -80, -60, -40, -20, 0, 20, 40, 60, 80, 100, 500,␣
↪1000])

height_ticks = np.array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 500, 1000])

# Compute transformed tick positions:


temp_tick_pos = transform_x(temp_ticks)
height_tick_pos = transform_y(height_ticks)

plt.xticks(temp_tick_pos, temp_ticks)
plt.yticks(height_tick_pos, height_ticks)

plt.xlabel("Temperature (°C)", fontsize=12)


plt.ylabel("Height (km)", fontsize=12)
plt.title("Earth's Atmospheric Temperature Profile (Custom Squeezed Scaling)",␣
↪fontsize=14)

plt.legend(fontsize=10)
plt.grid(True)

# Set limits to cover the entire transformed range


plt.xlim(transform_x(-100), transform_x(1000))
plt.ylim(transform_y(0), transform_y(1000))

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)

# Data for each layez


# Troposphere: 0 to 11 km
h_tropo = np.linspace(0, 11, 100)
T_tropo = 15 - 6.5 * h_tropo

# 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')

# Labels and title


plt.xlabel('Temperature (°C)')
plt.ylabel('Height (km)')
plt.title('Change in Atmospheric Temperature with Height')

# 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.plot(transform_temperature(-56.5), transform_height(11), 'ko',␣


↪markersize=8) # Tropopause
plt.annotate('Tropopause\n(-56.5°C, 11 km)',
xy=(transform_temperature(-56.5), transform_height(11)),
xytext=(-50, 12),
fontsize=10)

plt.plot(transform_temperature(0), transform_height(50), 'ko', markersize=8) #␣


↪Stratopause

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

# Define transformation functions for height and temperature


def transform_height(h):
h = np.asarray(h)

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

# Generate data for each atmospheric layer


# Troposphere (0-12 km)
troposphere_height = np.linspace(0, 12, 100)
troposphere_temp = 15 + (troposphere_height - 0) * (-56.5 - 15)/(12 - 0)

# Stratosphere (12-50 km)


stratosphere_height = np.linspace(12, 50, 100)
stratosphere_temp = -56.5 + (stratosphere_height - 12) * (-2.5 + 56.5)/(50 - 12)

# Mesosphere (50-85 km)


mesosphere_height = np.linspace(50, 85, 100)
mesosphere_temp = -2.5 + (mesosphere_height - 50) * (-90 + 2.5)/(85 - 50)

# Thermosphere (85-1000 km)


thermosphere_height = np.linspace(85, 1000, 100)
thermosphere_temp = -90 + (thermosphere_height - 85) * (1000 + 90)/(1000 - 85)

# Combine and transform data


heights = np.concatenate([troposphere_height, stratosphere_height,
mesosphere_height, thermosphere_height])
temps = np.concatenate([troposphere_temp, stratosphere_temp,
mesosphere_temp, thermosphere_temp])

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')

# Set axis ticks and labels


y_ticks = [0,10,20,30,40,50,60,70,80,90,100,500,1000]
plt.yticks(transform_height(y_ticks), labels=[str(y) for y in y_ticks])
plt.ylabel('Height (km)', fontsize=12)

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)

# Add atmospheric layer annotations


plt.text(15, 6, 'Troposphere', fontsize=10,
bbox=dict(facecolor='white', alpha=0.8))
plt.text(-70, 30, 'Stratosphere', fontsize=10,
bbox=dict(facecolor='white', alpha=0.8))
plt.text(-80, 70, 'Mesosphere', fontsize=10,
bbox=dict(facecolor='white', alpha=0.8))

# Thermosphere annotation in transformed coordinates


thermo_x = transform_temp(400)
thermo_y = transform_height(400)
plt.text(thermo_x, thermo_y, 'Thermosphere', fontsize=10,
bbox=dict(facecolor='white', alpha=0.8))

# Mark important pauses


plt.scatter(transform_temp(-56.5), transform_height(12), color='red', zorder=5)
plt.text(transform_temp(-56.5), transform_height(15), 'Tropopause\n(12 km, -56.
↪5°C)',

ha='right', va='bottom')

plt.scatter(transform_temp(-2.5), transform_height(50), color='red', zorder=5)


plt.text(transform_temp(-2.5), transform_height(55), 'Stratopause\n(50 km, -2.
↪5°C)',

ha='right', va='bottom')

plt.scatter(transform_temp(-90), transform_height(85), color='red', zorder=5)


plt.text(transform_temp(-95), transform_height(90), 'Mesopause\n(85 km, -90°C)',
ha='left', va='bottom')

# Set axis limits


plt.xlim(transform_temp(-100), transform_temp(1000))
plt.ylim(transform_height(0), transform_height(1000))

plt.tight_layout()
plt.show()

15
[74]: %config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)


y = np.cos(x)

plt.plot(x, y)
plt.xlabel("x")
plt.ylabel("cos(x)")
plt.title("High-Resolution Inline Plot")
plt.show()

16
[ ]:

17

You might also like