Python‐Matte - itnett/FTD02H-N GitHub Wiki
[python]
La oss begynne med å lage Python-kodeeksempler for hvert av de oppgitte emnene. Hvert eksempel vil være grundig kommentert, bruke standardverdier for demonstrasjon, generere grafiske utdata ved hjelp av Matplotlib, og inkludere utregninger som kan kopieres til GeoGebra.
1. Lineære ligninger
Vi starter med å løse en lineær ligning og plotte den.
import matplotlib.pyplot as plt
import numpy as np
def solve_linear_equation(a=1, b=-2):
"""
Solve the linear equation ax + b = 0 and plot it.
Parameters:
a (float): Coefficient of x
b (float): Constant term
Returns:
x (float): Solution of the equation
"""
# Calculate the solution
x = -b / a
# Generate points for the plot
x_values = np.linspace(-10, 10, 400)
y_values = a * x_values + b
# Plot the line
plt.plot(x_values, y_values, label=f'{a}x + {b} = 0')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.scatter([x], [0], color='red') # Solution point
plt.title('Linear Equation')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input: {a}*x + {b} = 0")
return x
# Example usage with default values
solve_linear_equation()
2. Kvadratiske ligninger
La oss lage et eksempel for å løse en kvadratisk ligning og plotte den.
import matplotlib.pyplot as plt
import numpy as np
def solve_quadratic_equation(a=1, b=0, c=-4):
"""
Solve the quadratic equation ax^2 + b^2 + c = 0 and plot it.
Parameters:
a (float): Coefficient of x^2
b (float): Coefficient of x
c (float): Constant term
Returns:
roots (tuple): Solutions of the equation
"""
# Calculate the discriminant
discriminant = b**2 - 4*a*c
# Calculate the two solutions
if discriminant >= 0:
root1 = (-b + np.sqrt(discriminant)) / (2 * a)
root2 = (-b - np.sqrt(discriminant)) / (2 * a)
else:
root1 = root2 = None
# Generate points for the plot
x_values = np.linspace(-10, 10, 400)
y_values = a * x_values**2 + b * x_values + c
# Plot the quadratic function
plt.plot(x_values, y_values, label=f'{a}x^2 + {b}x + {c} = 0')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
if root1 is not None and root2 is not None:
plt.scatter([root1, root2], [0, 0], color='red') # Solution points
plt.title('Quadratic Equation')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input: {a}*x^2 + {b}*x + {c} = 0")
return root1, root2
# Example usage with default values
solve_quadratic_equation()
3. Trigonometri
La oss lage et eksempel for å plotte sinus- og cosinusfunksjonene.
import matplotlib.pyplot as plt
import numpy as np
def plot_trigonometric_functions():
"""
Plot the sine and cosine functions.
"""
# Generate points for the plot
x_values = np.linspace(-2 * np.pi, 2 * np.pi, 400)
sin_values = np.sin(x_values)
cos_values = np.cos(x_values)
# Plot the sine function
plt.plot(x_values, sin_values, label='sin(x)')
plt.plot(x_values, cos_values, label='cos(x)')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.title('Trigonometric Functions')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print("GeoGebra input for sine: sin(x)")
print("GeoGebra input for cosine: cos(x)")
# Example usage
plot_trigonometric_functions()
4. Derivasjon
La oss lage et eksempel for å beregne den deriverte av en funksjon og plotte den.
import matplotlib.pyplot as plt
import numpy as np
import sympy as sp
def plot_derivative(a=1, b=0, c=0):
"""
Plot the function and its derivative.
Parameters:
a (float): Coefficient of x^2
b (float): Coefficient of x
c (float): Constant term
"""
# Define the function
x = sp.symbols('x')
function = a * x**2 + b * x + c
# Calculate the derivative
derivative = sp.diff(function, x)
# Convert to numerical functions
func = sp.lambdify(x, function, modules=['numpy'])
deriv = sp.lambdify(x, derivative, modules=['numpy'])
# Generate points for the plot
x_values = np.linspace(-10, 10, 400)
func_values = func(x_values)
deriv_values = deriv(x_values)
# Plot the function and its derivative
plt.plot(x_values, func_values, label=f'{a}x^2 + {b}x + {c}')
plt.plot(x_values, deriv_values, label=f'Derivative: {derivative}')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.title('Function and its Derivative')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input for function: {a}*x^2 + {b}*x + {c}")
print(f"GeoGebra input for derivative: {sp.printing.ccode(derivative)}")
# Example usage with default values
plot_derivative()
5. Integrasjon
La oss lage et eksempel for å beregne det bestemte integralet av en funksjon og plotte den.
import matplotlib.pyplot as plt
import numpy as np
import sympy as sp
def plot_integral(a=1, b=0, c=0, lower_limit=0, upper_limit=1):
"""
Plot the function and its definite integral over a given interval.
Parameters:
a (float): Coefficient of x^2
b (float): Coefficient of x
c (float): Constant term
lower_limit (float): Lower limit of integration
upper_limit (float): Upper limit of integration
"""
# Define the function
x = sp.symbols('x')
function = a * x**2 + b * x + c
# Calculate the definite integral
integral = sp.integrate(function, (x, lower_limit, upper_limit))
# Convert to numerical function
func = sp.lambdify(x, function, modules=['numpy'])
# Generate points for the plot
x_values = np.linspace(-10, 10, 400)
func_values = func(x_values)
# Plot the function
plt.plot(x_values, func_values, label=f'{a}x^2 + {b}x + {c}')
plt.fill_between(x_values, func_values, where=(x_values >= lower_limit) & (x_values <= upper_limit), color='grey', alpha=0.5)
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.title(f'Function and its Definite Integral from {lower_limit} to {upper_limit}')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input for function: {a}*x^2 + {b}*x + {c}")
print(f"GeoGebra input for integral: Integrate[{a}*x^2 + {b}*x + {c}, {lower_limit}, {upper_limit}] = {integral}")
# Example usage with default values
plot_integral()
6. Statistikk
La oss lage et eksempel for å beregne og plotte en normalfordeling.
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
def plot_normal_distribution(mean=0, std_dev=1):
"""
Plot the normal distribution.
Parameters:
mean (float): Mean of the distribution
std_dev (float): Standard deviation of the distribution
"""
# Generate points for the plot
x_values = np.linspace(mean - 4*std_dev, mean + 4*std_dev, 400)
y_values = stats.norm.pdf(x_values, mean, std_dev)
# Plot the normal distribution
plt.plot(x_values, y_values, label=f'N({mean}, {std_dev}^2)')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(mean, color='red', linestyle='dashed', linewidth=1) # Mean
plt.title('Normal Distribution')
plt.xlabel('x')
plt.ylabel('Probability Density')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input for normal distribution: Normal[{mean}, {std_dev}]")
# Example usage with default values
plot_normal_distribution()
7. Sannsynlighet
La oss lage et eksempel for å beregne og plotte en binomisk sannsynlighetsfordeling.
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
def plot_binomial_distribution(n=10, p=0.5):
"""
Plot the binomial distribution.
Parameters:
n (int): Number of trials
p (float): Probability of success in each trial
"""
# Generate points for the plot
x_values = np.arange(0, n+1)
y_values = stats.binom.pmf(x_values, n, p)
# Plot the binomial distribution
plt.stem(x_values, y_values, use_line_collection=True)
plt.title(f'Binomial Distribution (n={n}, p={p})')
plt.xlabel('Number of successes')
plt.ylabel('Probability')
plt.grid(True)
plt.show()
print(f"GeoGebra input for binomial distribution: Binomial[{n}, {p}]")
# Example usage with default values
plot_binomial_distribution()
Vennligst bekreft at disse eksemplene dekker dine behov, eller gi beskjed om eventuelle justeringer eller ytterligere emner du vil inkludere.
[python]
La oss lage Python-kodeeksempler for de matematiske og fysiske temaene som er oppført i emnebeskrivelsen. Hvert eksempel vil være godt kommentert, bruke standardverdier for demonstrasjon, generere grafiske utdata, og inkludere utregninger som kan kopieres til GeoGebra.
Algebra
Regneregler, Brøk og prosentregning, Potenser, Tall på standardform
def algebra_examples():
# Eksempler på algebraiske operasjoner
# Potensregning
base = 2
exponent = 3
power = base ** exponent
print(f"{base} opphøyd i {exponent} er {power}")
# Brøkregning
numerator = 3
denominator = 4
fraction = numerator / denominator
print(f"Brøken {numerator}/{denominator} er lik {fraction}")
# Prosentregning
total = 200
percent = 15
percentage_value = (percent / 100) * total
print(f"{percent}% av {total} er {percentage_value}")
# Tall på standardform
number = 5.67e3
print(f"Tallet i standardform er {number}")
algebra_examples()
Sammentrekning og faktorisering
import sympy as sp
def factor_expression(expr='x**2 - 4'):
"""
Factor a given algebraic expression.
Parameters:
expr (str): The algebraic expression to be factored.
"""
x = sp.symbols('x')
expression = sp.sympify(expr)
factored_expression = sp.factor(expression)
print(f"Faktorisering av {expr}: {factored_expression}")
print(f"GeoGebra input: Factor[{expr}]")
# Example usage
factor_expression()
Likninger og formelregning
Løse likninger av første og andre grad
import numpy as np
import matplotlib.pyplot as plt
def solve_and_plot_linear_equation(a=1, b=-2):
"""
Solve and plot a linear equation ax + b = 0.
Parameters:
a (float): Coefficient of x.
b (float): Constant term.
Returns:
x (float): Solution of the equation.
"""
x = -b / a
x_values = np.linspace(-10, 10, 400)
y_values = a * x_values + b
plt.plot(x_values, y_values, label=f'{a}x + {b} = 0')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.scatter([x], [0], color='red')
plt.title('Linear Equation')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input: {a}*x + {b} = 0")
return x
# Example usage
solve_and_plot_linear_equation()
def solve_and_plot_quadratic_equation(a=1, b=0, c=-4):
"""
Solve and plot a quadratic equation ax^2 + bx + c = 0.
Parameters:
a (float): Coefficient of x^2.
b (float): Coefficient of x.
c (float): Constant term.
Returns:
tuple: Solutions of the equation.
"""
discriminant = b**2 - 4*a*c
if discriminant >= 0:
root1 = (-b + np.sqrt(discriminant)) / (2 * a)
root2 = (-b - np.sqrt(discriminant)) / (2 * a)
else:
root1 = root2 = None
x_values = np.linspace(-10, 10, 400)
y_values = a * x_values**2 + b * x_values + c
plt.plot(x_values, y_values, label=f'{a}x^2 + {b}x + {c} = 0')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
if root1 is not None and root2 is not None:
plt.scatter([root1, root2], [0, 0], color='red')
plt.title('Quadratic Equation')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input: {a}*x^2 + {b}*x + {c} = 0")
return root1, root2
# Example usage
solve_and_plot_quadratic_equation()
Løse likningssett med to ukjente
import numpy as np
def solve_linear_system(a1=1, b1=2, c1=3, a2=4, b2=5, c2=6):
"""
Solve a system of linear equations:
a1*x + b1*y = c1
a2*x + b2*y = c2
Parameters:
a1, b1, c1, a2, b2, c2 (float): Coefficients of the equations.
Returns:
tuple: Solutions for x and y.
"""
A = np.array([a1, b1], [a2, b2](/itnett/FTD02H-N/wiki/a1,-b1],-[a2,-b2))
B = np.array([c1, c2])
solutions = np.linalg.solve(A, B)
x, y = solutions[0], solutions[1]
print(f"Løsning: x = {x}, y = {y}")
print(f"GeoGebra input: Solve[{a1}x + {b1}y = {c1}, {a2}x + {b2}y = {c2}]")
return x, y
# Example usage
solve_linear_system()
Trigonometri og geometri
Areal, omkrets, volum og overflate
import math
def geometry_examples():
# Areal og omkrets av en sirkel
radius = 5
area_circle = math.pi * radius**2
circumference_circle = 2 * math.pi * radius
print(f"Arealet av en sirkel med radius {radius} er {area_circle}")
print(f"Omkretsen av en sirkel med radius {radius} er {circumference_circle}")
# Volum og overflate av en kule
volume_sphere = (4/3) * math.pi * radius**3
surface_area_sphere = 4 * math.pi * radius**2
print(f"Volumet av en kule med radius {radius} er {volume_sphere}")
print(f"Overflaten av en kule med radius {radius} er {surface_area_sphere}")
# GeoGebra input
print(f"GeoGebra input for sirkel: Circle[(0, 0), {radius}]")
print(f"GeoGebra input for kule: Sphere[(0, 0, 0), {radius}]")
geometry_examples()
Pytagoras' setning og Trigonometri i rettvinklede trekanter
import math
def pythagorean_theorem(a=3, b=4):
"""
Calculate the hypotenuse of a right triangle using Pythagoras' theorem.
Parameters:
a (float): One leg of the triangle.
b (float): The other leg of the triangle.
Returns:
c (float): The hypotenuse of the triangle.
"""
c = math.sqrt(a**2 + b**2)
print(f"Med sidene a={a} og b={b} er hypotenusen c={c}")
print(f"GeoGebra input: c = sqrt({a}^2 + {b}^2)")
return c
def trigonometry_right_triangle(angle_degrees=30, hypotenuse=1):
"""
Calculate the lengths of the legs of a right triangle given an angle and the hypotenuse.
Parameters:
angle_degrees (float): Angle in degrees.
hypotenuse (float): The hypotenuse of the triangle.
Returns:
(float, float): The lengths of the opposite and adjacent sides.
"""
angle_radians = math.radians(angle_degrees)
opposite = hypotenuse * math.sin(angle_radians)
adjacent = hypotenuse * math.cos(angle_radians)
print(f"Med hypotenusen {hypotenuse} og vinkelen {angle_degrees} grader er:")
print(f"Motstående side = {opposite}")
print(f"Tilstøtende side = {adjacent}")
print(f"GeoGebra input: sin({angle_degrees}) = {opposite}/{hypotenuse}, cos({angle_degrees}) = {adjacent}/{hypotenuse}")
return opposite, adjacent
# Example usage
pythagorean_theorem()
trigonometry_right_triangle()
Vektorer i planet
import numpy as np
import matplotlib.pyplot as plt
def plot
_vectors(v1=(1, 2), v2=(3, 4)):
"""
Plot two vectors in the plane.
Parameters:
v1, v2 (tuple): Coordinates of the vectors.
"""
origin = np.array([0, 0])
v1 = np.array(v1)
v2 = np.array(v2)
plt.quiver(*origin, *v1, color='r', scale=1, scale_units='xy', angles='xy', label='v1')
plt.quiver(*origin, *v2, color='b', scale=1, scale_units='xy', angles='xy', label='v2')
plt.xlim(-1, 5)
plt.ylim(-1, 5)
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.grid()
plt.legend()
plt.show()
print(f"GeoGebra input for v1: Vector[(0, 0), ({v1[0]}, {v1[1]})]")
print(f"GeoGebra input for v2: Vector[(0, 0), ({v2[0]}, {v2[1]})]")
# Example usage
plot_vectors()
Funksjoner
Rette linjer, Polynomfunksjoner, Eksponentialfunksjoner
import numpy as np
import matplotlib.pyplot as plt
def plot_linear_function(m=1, c=0):
"""
Plot a linear function y = mx + c.
Parameters:
m (float): Slope of the line.
c (float): y-intercept.
"""
x = np.linspace(-10, 10, 400)
y = m * x + c
plt.plot(x, y, label=f'y = {m}x + {c}')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.title('Linear Function')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input: y = {m}x + {c}")
def plot_polynomial_function(coeffs=[1, 0, -4]):
"""
Plot a polynomial function.
Parameters:
coeffs (list): List of coefficients [a_n, a_(n-1), ..., a_1, a_0].
"""
p = np.poly1d(coeffs)
x = np.linspace(-10, 10, 400)
y = p(x)
plt.plot(x, y, label=f'y = {" ".join([f"{a}x^{i}" for i, a in enumerate(coeffs[::-1])])}')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.title('Polynomial Function')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input: Polynomial[{', '.join(map(str, coeffs))}]")
def plot_exponential_function(base=2):
"""
Plot an exponential function y = base^x.
Parameters:
base (float): Base of the exponential function.
"""
x = np.linspace(-2, 2, 400)
y = base ** x
plt.plot(x, y, label=f'y = {base}^x')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.title('Exponential Function')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input: y = {base}^x")
# Example usage
plot_linear_function()
plot_polynomial_function()
plot_exponential_function()
Derivasjon av polynomfunksjoner
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
def plot_derivative(coeffs=[1, 0, -4]):
"""
Plot a polynomial function and its derivative.
Parameters:
coeffs (list): List of coefficients [a_n, a_(n-1), ..., a_1, a_0].
"""
x = sp.symbols('x')
polynomial = sum(c * x**i for i, c in enumerate(coeffs))
derivative = sp.diff(polynomial, x)
p = sp.lambdify(x, polynomial, 'numpy')
d = sp.lambdify(x, derivative, 'numpy')
x_vals = np.linspace(-10, 10, 400)
y_vals = p(x_vals)
dy_vals = d(x_vals)
plt.plot(x_vals, y_vals, label=f'Polynomial: {polynomial}')
plt.plot(x_vals, dy_vals, label=f'Derivative: {derivative}')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.title('Polynomial and its Derivative')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input for polynomial: {polynomial}")
print(f"GeoGebra input for derivative: {derivative}")
# Example usage
plot_derivative()
Regresjon ved hjelp av digitale hjelpemidler
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
def perform_linear_regression(x_data=[1, 2, 3, 4, 5], y_data=[2, 4, 5, 4, 5]):
"""
Perform linear regression on a set of data points and plot the result.
Parameters:
x_data (list): List of x-coordinates of the data points.
y_data (list): List of y-coordinates of the data points.
"""
x = np.array(x_data).reshape(-1, 1)
y = np.array(y_data)
model = LinearRegression()
model.fit(x, y)
y_pred = model.predict(x)
plt.scatter(x, y, color='blue', label='Data points')
plt.plot(x, y_pred, color='red', label='Linear regression line')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.title('Linear Regression')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input for data points: List of points (x, y)")
print(f"GeoGebra input for regression line: y = {model.coef_[0]}*x + {model.intercept_}")
# Example usage
perform_linear_regression()
Innledende emner i fysikk
Anvende SI-systemet og dekadiske prefikser
def si_units_examples():
# Eksempler på SI-enheter og dekadiske prefikser
length_in_meters = 1.0 # meter
length_in_kilometers = length_in_meters / 1000 # kilometer
length_in_millimeters = length_in_meters * 1000 # millimeter
print(f"Lengde: {length_in_meters} meter, {length_in_kilometers} kilometer, {length_in_millimeters} millimeter")
mass_in_grams = 1000 # gram
mass_in_kilograms = mass_in_grams / 1000 # kilogram
mass_in_milligrams = mass_in_grams * 1000 # milligram
print(f"Masse: {mass_in_grams} gram, {mass_in_kilograms} kilogram, {mass_in_milligrams} milligram")
time_in_seconds = 3600 # sekunder
time_in_hours = time_in_seconds / 3600 # timer
time_in_minutes = time_in_seconds / 60 # minutter
print(f"Tid: {time_in_seconds} sekunder, {time_in_hours} timer, {time_in_minutes} minutter")
si_units_examples()
Begrepene masse, tyngde og massetetthet
def physics_concepts(mass_kg=70, volume_m3=0.07):
"""
Calculate weight and density from mass and volume.
Parameters:
mass_kg (float): Mass in kilograms.
volume_m3 (float): Volume in cubic meters.
Returns:
tuple: Weight in newtons, density in kg/m^3.
"""
g = 9.81 # acceleration due to gravity in m/s^2
weight = mass_kg * g # weight in newtons
density = mass_kg / volume_m3 # density in kg/m^3
print(f"Masse: {mass_kg} kg")
print
(f"Tyngde: {weight} N")
print(f"Massetetthet: {density} kg/m^3")
return weight, density
# Example usage
physics_concepts()
Usikkerhet og korrekt bruk av gjeldende siffer
def significant_figures(value=1234.567, significant_digits=4):
"""
Round a value to a specified number of significant digits.
Parameters:
value (float): The value to round.
significant_digits (int): The number of significant digits.
Returns:
float: The value rounded to the specified number of significant digits.
"""
from decimal import Decimal
rounded_value = round(Decimal(value), significant_digits - 1 - int(Decimal(value).adjusted()))
print(f"Verdi: {value} avrundet til {significant_digits} gjeldende siffer er {rounded_value}")
return rounded_value
# Example usage
significant_figures()
Kraft og rettlinjet bevegelse
def newtons_laws(force_n=10, mass_kg=2):
"""
Calculate acceleration using Newton's second law.
Parameters:
force_n (float): Force in newtons.
mass_kg (float): Mass in kilograms.
Returns:
float: Acceleration in m/s^2.
"""
acceleration = force_n / mass_kg
print(f"Med kraft {force_n} N og masse {mass_kg} kg er akselerasjonen {acceleration} m/s^2")
return acceleration
def motion_equations(v0=0, a=9.81, t=1):
"""
Calculate the position and velocity using motion equations for constant acceleration.
Parameters:
v0 (float): Initial velocity in m/s.
a (float): Acceleration in m/s^2.
t (float): Time in seconds.
Returns:
tuple: Final position in meters, final velocity in m/s.
"""
v = v0 + a * t
s = v0 * t + 0.5 * a * t**2
print(f"Med initial hastighet {v0} m/s, akselerasjon {a} m/s^2 og tid {t} s er sluttposisjonen {s} m og sluthastigheten {v} m/s")
return s, v
# Example usage
newtons_laws()
motion_equations()
Energi
Beregne arbeid, effekt og virkningsgrad
def work_power_efficiency(force_n=10, distance_m=5, time_s=2, efficiency=0.8):
"""
Calculate work, power, and efficiency.
Parameters:
force_n (float): Force in newtons.
distance_m (float): Distance in meters.
time_s (float): Time in seconds.
efficiency (float): Efficiency as a fraction.
Returns:
tuple: Work in joules, power in watts, efficient power in watts.
"""
work = force_n * distance_m
power = work / time_s
efficient_power = power * efficiency
print(f"Arbeid: {work} J")
print(f"Effekt: {power} W")
print(f"Effektiv effekt (virkningsgrad {efficiency*100}%): {efficient_power} W")
return work, power, efficient_power
# Example usage
work_power_efficiency()
Beregne kinetisk og potensiell energi
def kinetic_potential_energy(mass_kg=2, height_m=10, velocity_m_s=5):
"""
Calculate kinetic and potential energy.
Parameters:
mass_kg (float): Mass in kilograms.
height_m (float): Height in meters.
velocity_m_s (float): Velocity in meters per second.
Returns:
tuple: Kinetic energy in joules, potential energy in joules.
"""
g = 9.81 # acceleration due to gravity in m/s^2
kinetic_energy = 0.5 * mass_kg * velocity_m_s**2
potential_energy = mass_kg * g * height_m
print(f"Kinetisk energi: {kinetic_energy} J")
print(f"Potensiell energi: {potential_energy} J")
return kinetic_energy, potential_energy
# Example usage
kinetic_potential_energy()
Anvende energibevaring og Termodynamikkens første lov
def energy_conservation(mass_kg=2, height_m=10, velocity_m_s=5):
"""
Demonstrate the principle of energy conservation.
Parameters:
mass_kg (float): Mass in kilograms.
height_m (float): Height in meters.
velocity_m_s (float): Velocity in meters per second.
Returns:
float: Total mechanical energy in joules.
"""
kinetic_energy, potential_energy = kinetic_potential_energy(mass_kg, height_m, velocity_m_s)
total_energy = kinetic_energy + potential_energy
print(f"Total mekanisk energi (kinetisk + potensiell): {total_energy} J")
return total_energy
def first_law_of_thermodynamics(internal_energy_change=500, heat_added=300):
"""
Apply the first law of thermodynamics.
Parameters:
internal_energy_change (float): Change in internal energy in joules.
heat_added (float): Heat added in joules.
Returns:
float: Work done in joules.
"""
work_done = heat_added - internal_energy_change
print(f"I henhold til termodynamikkens første lov, med endring i indre energi {internal_energy_change} J og tilført varme {heat_added} J, er utført arbeid {work_done} J")
return work_done
# Example usage
energy_conservation()
first_law_of_thermodynamics()
Studieretningsspesifikke temaer
Briggske logaritmer
import math
def briggs_logarithms(value=1000):
"""
Calculate the Briggs logarithm (base 10) of a given value.
Parameters:
value (float): The value for which to calculate the logarithm.
Returns:
float: The logarithm (base 10) of the value.
"""
log_value = math.log10(value)
print(f"Briggs logaritme (base 10) av {value} er {log_value}")
return log_value
# Example usage
briggs_logarithms()
Kombinatorikk
import math
def combinations(n=5, k=2):
"""
Calculate the number of combinations (n choose k).
Parameters:
n (int): Total number of items.
k (int): Number of items to choose.
Returns:
int: Number of combinations.
"""
comb = math.comb(n, k)
print(f"Antall kombinasjoner av {n} gjenstander tatt {k} av gangen er {comb}")
return comb
# Example usage
combinations()
Sannsynlighetsregning og statistikk
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
def plot_normal_distribution(mean=0, std_dev=1):
"""
Plot the normal distribution.
Parameters:
mean (float): Mean of the distribution.
std_dev (float): Standard deviation of the distribution.
"""
x_values = np.linspace(mean - 4*std_dev, mean + 4*std_dev, 400)
y_values = stats.norm.pdf(x_values, mean, std_dev)
plt.plot(x_values, y_values, label=f'N({mean}, {std_dev}^2)')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(mean, color='red', linestyle='dashed', linewidth=1)
plt.title('Normal Distribution')
plt.xlabel('x')
plt.
[python]
La oss lage Python-kodeeksempler for de matematiske og fysiske temaene som er oppført i emnebeskrivelsen. Hvert eksempel vil være godt kommentert, bruke standardverdier for demonstrasjon, generere grafiske utdata, og inkludere utregninger som kan kopieres til GeoGebra.
### Algebra
#### Regneregler, Brøk og prosentregning, Potenser, Tall på standardform
```python
def algebra_examples():
# Eksempler på algebraiske operasjoner
# Potensregning
base = 2
exponent = 3
power = base ** exponent
print(f"{base} opphøyd i {exponent} er {power}")
# Brøkregning
numerator = 3
denominator = 4
fraction = numerator / denominator
print(f"Brøken {numerator}/{denominator} er lik {fraction}")
# Prosentregning
total = 200
percent = 15
percentage_value = (percent / 100) * total
print(f"{percent}% av {total} er {percentage_value}")
# Tall på standardform
number = 5.67e3
print(f"Tallet i standardform er {number}")
algebra_examples()
Sammentrekning og faktorisering
import sympy as sp
def factor_expression(expr='x**2 - 4'):
"""
Factor a given algebraic expression.
Parameters:
expr (str): The algebraic expression to be factored.
"""
x = sp.symbols('x')
expression = sp.sympify(expr)
factored_expression = sp.factor(expression)
print(f"Faktorisering av {expr}: {factored_expression}")
print(f"GeoGebra input: Factor[{expr}]")
# Example usage
factor_expression()
Likninger og formelregning
Løse likninger av første og andre grad
import numpy as np
import matplotlib.pyplot as plt
def solve_and_plot_linear_equation(a=1, b=-2):
"""
Solve and plot a linear equation ax + b = 0.
Parameters:
a (float): Coefficient of x.
b (float): Constant term.
Returns:
x (float): Solution of the equation.
"""
x = -b / a
x_values = np.linspace(-10, 10, 400)
y_values = a * x_values + b
plt.plot(x_values, y_values, label=f'{a}x + {b} = 0')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.scatter([x], [0], color='red')
plt.title('Linear Equation')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input: {a}*x + {b} = 0")
return x
# Example usage
solve_and_plot_linear_equation()
def solve_and_plot_quadratic_equation(a=1, b=0, c=-4):
"""
Solve and plot a quadratic equation ax^2 + bx + c = 0.
Parameters:
a (float): Coefficient of x^2.
b (float): Coefficient of x.
c (float): Constant term.
Returns:
tuple: Solutions of the equation.
"""
discriminant = b**2 - 4*a*c
if discriminant >= 0:
root1 = (-b + np.sqrt(discriminant)) / (2 * a)
root2 = (-b - np.sqrt(discriminant)) / (2 * a)
else:
root1 = root2 = None
x_values = np.linspace(-10, 10, 400)
y_values = a * x_values**2 + b * x_values + c
plt.plot(x_values, y_values, label=f'{a}x^2 + {b}x + {c} = 0')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
if root1 is not None and root2 is not None:
plt.scatter([root1, root2], [0, 0], color='red')
plt.title('Quadratic Equation')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input: {a}*x^2 + {b}*x + {c} = 0")
return root1, root2
# Example usage
solve_and_plot_quadratic_equation()
Løse likningssett med to ukjente
import numpy as np
def solve_linear_system(a1=1, b1=2, c1=3, a2=4, b2=5, c2=6):
"""
Solve a system of linear equations:
a1*x + b1*y = c1
a2*x + b2*y = c2
Parameters:
a1, b1, c1, a2, b2, c2 (float): Coefficients of the equations.
Returns:
tuple: Solutions for x and y.
"""
A = np.array([a1, b1], [a2, b2](/itnett/FTD02H-N/wiki/a1,-b1],-[a2,-b2))
B = np.array([c1, c2])
solutions = np.linalg.solve(A, B)
x, y = solutions[0], solutions[1]
print(f"Løsning: x = {x}, y = {y}")
print(f"GeoGebra input: Solve[{a1}x + {b1}y = {c1}, {a2}x + {b2}y = {c2}]")
return x, y
# Example usage
solve_linear_system()
Trigonometri og geometri
Areal, omkrets, volum og overflate
import math
def geometry_examples():
# Areal og omkrets av en sirkel
radius = 5
area_circle = math.pi * radius**2
circumference_circle = 2 * math.pi * radius
print(f"Arealet av en sirkel med radius {radius} er {area_circle}")
print(f"Omkretsen av en sirkel med radius {radius} er {circumference_circle}")
# Volum og overflate av en kule
volume_sphere = (4/3) * math.pi * radius**3
surface_area_sphere = 4 * math.pi * radius**2
print(f"Volumet av en kule med radius {radius} er {volume_sphere}")
print(f"Overflaten av en kule med radius {radius} er {surface_area_sphere}")
# GeoGebra input
print(f"GeoGebra input for sirkel: Circle[(0, 0), {radius}]")
print(f"GeoGebra input for kule: Sphere[(0, 0, 0), {radius}]")
geometry_examples()
Pytagoras' setning og Trigonometri i rettvinklede trekanter
import math
def pythagorean_theorem(a=3, b=4):
"""
Calculate the hypotenuse of a right triangle using Pythagoras' theorem.
Parameters:
a (float): One leg of the triangle.
b (float): The other leg of the triangle.
Returns:
c (float): The hypotenuse of the triangle.
"""
c = math.sqrt(a**2 + b**2)
print(f"Med sidene a={a} og b={b} er hypotenusen c={c}")
print(f"GeoGebra input: c = sqrt({a}^2 + {b}^2)")
return c
def trigonometry_right_triangle(angle_degrees=30, hypotenuse=1):
"""
Calculate the lengths of the legs of a right triangle given an angle and the hypotenuse.
Parameters:
angle_degrees (float): Angle in degrees.
hypotenuse (float): The hypotenuse of the triangle.
Returns:
(float, float): The lengths of the opposite and adjacent sides.
"""
angle_radians = math.radians(angle_degrees)
opposite = hypotenuse * math.sin(angle_radians)
adjacent = hypotenuse * math.cos(angle_radians)
print(f"Med hypotenusen {hypotenuse} og vinkelen {angle_degrees} grader er:")
print(f"Motstående side = {opposite}")
print(f"Tilstøtende side = {adjacent}")
print(f"GeoGebra input: sin({angle_degrees}) = {opposite}/{hypotenuse}, cos({angle_degrees}) = {adjacent}/{hypotenuse}")
return opposite, adjacent
# Example usage
pythagorean_theorem()
trigonometry_right_triangle()
Vektorer i planet
import numpy as np
import matplotlib.pyplot as plt
def plot
_vectors(v1=(1, 2), v2=(3, 4)):
"""
Plot two vectors in the plane.
Parameters:
v1, v2 (tuple): Coordinates of the vectors.
"""
origin = np.array([0, 0])
v1 = np.array(v1)
v2 = np.array(v2)
plt.quiver(*origin, *v1, color='r', scale=1, scale_units='xy', angles='xy', label='v1')
plt.quiver(*origin, *v2, color='b', scale=1, scale_units='xy', angles='xy', label='v2')
plt.xlim(-1, 5)
plt.ylim(-1, 5)
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.grid()
plt.legend()
plt.show()
print(f"GeoGebra input for v1: Vector[(0, 0), ({v1[0]}, {v1[1]})]")
print(f"GeoGebra input for v2: Vector[(0, 0), ({v2[0]}, {v2[1]})]")
# Example usage
plot_vectors()
Funksjoner
Rette linjer, Polynomfunksjoner, Eksponentialfunksjoner
import numpy as np
import matplotlib.pyplot as plt
def plot_linear_function(m=1, c=0):
"""
Plot a linear function y = mx + c.
Parameters:
m (float): Slope of the line.
c (float): y-intercept.
"""
x = np.linspace(-10, 10, 400)
y = m * x + c
plt.plot(x, y, label=f'y = {m}x + {c}')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.title('Linear Function')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input: y = {m}x + {c}")
def plot_polynomial_function(coeffs=[1, 0, -4]):
"""
Plot a polynomial function.
Parameters:
coeffs (list): List of coefficients [a_n, a_(n-1), ..., a_1, a_0].
"""
p = np.poly1d(coeffs)
x = np.linspace(-10, 10, 400)
y = p(x)
plt.plot(x, y, label=f'y = {" ".join([f"{a}x^{i}" for i, a in enumerate(coeffs[::-1])])}')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.title('Polynomial Function')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input: Polynomial[{', '.join(map(str, coeffs))}]")
def plot_exponential_function(base=2):
"""
Plot an exponential function y = base^x.
Parameters:
base (float): Base of the exponential function.
"""
x = np.linspace(-2, 2, 400)
y = base ** x
plt.plot(x, y, label=f'y = {base}^x')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.title('Exponential Function')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input: y = {base}^x")
# Example usage
plot_linear_function()
plot_polynomial_function()
plot_exponential_function()
Derivasjon av polynomfunksjoner
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
def plot_derivative(coeffs=[1, 0, -4]):
"""
Plot a polynomial function and its derivative.
Parameters:
coeffs (list): List of coefficients [a_n, a_(n-1), ..., a_1, a_0].
"""
x = sp.symbols('x')
polynomial = sum(c * x**i for i, c in enumerate(coeffs))
derivative = sp.diff(polynomial, x)
p = sp.lambdify(x, polynomial, 'numpy')
d = sp.lambdify(x, derivative, 'numpy')
x_vals = np.linspace(-10, 10, 400)
y_vals = p(x_vals)
dy_vals = d(x_vals)
plt.plot(x_vals, y_vals, label=f'Polynomial: {polynomial}')
plt.plot(x_vals, dy_vals, label=f'Derivative: {derivative}')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.title('Polynomial and its Derivative')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input for polynomial: {polynomial}")
print(f"GeoGebra input for derivative: {derivative}")
# Example usage
plot_derivative()
Regresjon ved hjelp av digitale hjelpemidler
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
def perform_linear_regression(x_data=[1, 2, 3, 4, 5], y_data=[2, 4, 5, 4, 5]):
"""
Perform linear regression on a set of data points and plot the result.
Parameters:
x_data (list): List of x-coordinates of the data points.
y_data (list): List of y-coordinates of the data points.
"""
x = np.array(x_data).reshape(-1, 1)
y = np.array(y_data)
model = LinearRegression()
model.fit(x, y)
y_pred = model.predict(x)
plt.scatter(x, y, color='blue', label='Data points')
plt.plot(x, y_pred, color='red', label='Linear regression line')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.title('Linear Regression')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)
plt.show()
print(f"GeoGebra input for data points: List of points (x, y)")
print(f"GeoGebra input for regression line: y = {model.coef_[0]}*x + {model.intercept_}")
# Example usage
perform_linear_regression()
Innledende emner i fysikk
Anvende SI-systemet og dekadiske prefikser
def si_units_examples():
# Eksempler på SI-enheter og dekadiske prefikser
length_in_meters = 1.0 # meter
length_in_kilometers = length_in_meters / 1000 # kilometer
length_in_millimeters = length_in_meters * 1000 # millimeter
print(f"Lengde: {length_in_meters} meter, {length_in_kilometers} kilometer, {length_in_millimeters} millimeter")
mass_in_grams = 1000 # gram
mass_in_kilograms = mass_in_grams / 1000 # kilogram
mass_in_milligrams = mass_in_grams * 1000 # milligram
print(f"Masse: {mass_in_grams} gram, {mass_in_kilograms} kilogram, {mass_in_milligrams} milligram")
time_in_seconds = 3600 # sekunder
time_in_hours = time_in_seconds / 3600 # timer
time_in_minutes = time_in_seconds / 60 # minutter
print(f"Tid: {time_in_seconds} sekunder, {time_in_hours} timer, {time_in_minutes} minutter")
si_units_examples()
Begrepene masse, tyngde og massetetthet
def physics_concepts(mass_kg=70, volume_m3=0.07):
"""
Calculate weight and density from mass and volume.
Parameters:
mass_kg (float): Mass in kilograms.
volume_m3 (float): Volume in cubic meters.
Returns:
tuple: Weight in newtons, density in kg/m^3.
"""
g = 9.81 # acceleration due to gravity in m/s^2
weight = mass_kg * g # weight in newtons
density = mass_kg / volume_m3 # density in kg/m^3
print(f"Masse: {mass_kg} kg")
print
(f"Tyngde: {weight} N")
print(f"Massetetthet: {density} kg/m^3")
return weight, density
# Example usage
physics_concepts()
Usikkerhet og korrekt bruk av gjeldende siffer
def significant_figures(value=1234.567, significant_digits=4):
"""
Round a value to a specified number of significant digits.
Parameters:
value (float): The value to round.
significant_digits (int): The number of significant digits.
Returns:
float: The value rounded to the specified number of significant digits.
"""
from decimal import Decimal
rounded_value = round(Decimal(value), significant_digits - 1 - int(Decimal(value).adjusted()))
print(f"Verdi: {value} avrundet til {significant_digits} gjeldende siffer er {rounded_value}")
return rounded_value
# Example usage
significant_figures()
Kraft og rettlinjet bevegelse
def newtons_laws(force_n=10, mass_kg=2):
"""
Calculate acceleration using Newton's second law.
Parameters:
force_n (float): Force in newtons.
mass_kg (float): Mass in kilograms.
Returns:
float: Acceleration in m/s^2.
"""
acceleration = force_n / mass_kg
print(f"Med kraft {force_n} N og masse {mass_kg} kg er akselerasjonen {acceleration} m/s^2")
return acceleration
def motion_equations(v0=0, a=9.81, t=1):
"""
Calculate the position and velocity using motion equations for constant acceleration.
Parameters:
v0 (float): Initial velocity in m/s.
a (float): Acceleration in m/s^2.
t (float): Time in seconds.
Returns:
tuple: Final position in meters, final velocity in m/s.
"""
v = v0 + a * t
s = v0 * t + 0.5 * a * t**2
print(f"Med initial hastighet {v0} m/s, akselerasjon {a} m/s^2 og tid {t} s er sluttposisjonen {s} m og sluthastigheten {v} m/s")
return s, v
# Example usage
newtons_laws()
motion_equations()
Energi
Beregne arbeid, effekt og virkningsgrad
def work_power_efficiency(force_n=10, distance_m=5, time_s=2, efficiency=0.8):
"""
Calculate work, power, and efficiency.
Parameters:
force_n (float): Force in newtons.
distance_m (float): Distance in meters.
time_s (float): Time in seconds.
efficiency (float): Efficiency as a fraction.
Returns:
tuple: Work in joules, power in watts, efficient power in watts.
"""
work = force_n * distance_m
power = work / time_s
efficient_power = power * efficiency
print(f"Arbeid: {work} J")
print(f"Effekt: {power} W")
print(f"Effektiv effekt (virkningsgrad {efficiency*100}%): {efficient_power} W")
return work, power, efficient_power
# Example usage
work_power_efficiency()
Beregne kinetisk og potensiell energi
def kinetic_potential_energy(mass_kg=2, height_m=10, velocity_m_s=5):
"""
Calculate kinetic and potential energy.
Parameters:
mass_kg (float): Mass in kilograms.
height_m (float): Height in meters.
velocity_m_s (float): Velocity in meters per second.
Returns:
tuple: Kinetic energy in joules, potential energy in joules.
"""
g = 9.81 # acceleration due to gravity in m/s^2
kinetic_energy = 0.5 * mass_kg * velocity_m_s**2
potential_energy = mass_kg * g * height_m
print(f"Kinetisk energi: {kinetic_energy} J")
print(f"Potensiell energi: {potential_energy} J")
return kinetic_energy, potential_energy
# Example usage
kinetic_potential_energy()
Anvende energibevaring og Termodynamikkens første lov
def energy_conservation(mass_kg=2, height_m=10, velocity_m_s=5):
"""
Demonstrate the principle of energy conservation.
Parameters:
mass_kg (float): Mass in kilograms.
height_m (float): Height in meters.
velocity_m_s (float): Velocity in meters per second.
Returns:
float: Total mechanical energy in joules.
"""
kinetic_energy, potential_energy = kinetic_potential_energy(mass_kg, height_m, velocity_m_s)
total_energy = kinetic_energy + potential_energy
print(f"Total mekanisk energi (kinetisk + potensiell): {total_energy} J")
return total_energy
def first_law_of_thermodynamics(internal_energy_change=500, heat_added=300):
"""
Apply the first law of thermodynamics.
Parameters:
internal_energy_change (float): Change in internal energy in joules.
heat_added (float): Heat added in joules.
Returns:
float: Work done in joules.
"""
work_done = heat_added - internal_energy_change
print(f"I henhold til termodynamikkens første lov, med endring i indre energi {internal_energy_change} J og tilført varme {heat_added} J, er utført arbeid {work_done} J")
return work_done
# Example usage
energy_conservation()
first_law_of_thermodynamics()
Studieretningsspesifikke temaer
Briggske logaritmer
import math
def briggs_logarithms(value=1000):
"""
Calculate the Briggs logarithm (base 10) of a given value.
Parameters:
value (float): The value for which to calculate the logarithm.
Returns:
float: The logarithm (base 10) of the value.
"""
log_value = math.log10(value)
print(f"Briggs logaritme (base 10) av {value} er {log_value}")
return log_value
# Example usage
briggs_logarithms()
Kombinatorikk
import math
def combinations(n=5, k=2):
"""
Calculate the number of combinations (n choose k).
Parameters:
n (int): Total number of items.
k (int): Number of items to choose.
Returns:
int: Number of combinations.
"""
comb = math.comb(n, k)
print(f"Antall kombinasjoner av {n} gjenstander tatt {k} av gangen er {comb}")
return comb
# Example usage
combinations()
Sannsynlighetsregning og statistikk
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
def plot_normal_distribution(mean=0, std_dev=1):
"""
Plot the normal distribution.
Parameters:
mean (float): Mean of the distribution.
std_dev (float): Standard deviation of the distribution.
"""
x_values = np.linspace(mean - 4*std_dev, mean + 4*std_dev, 400)
y_values = stats.norm.pdf(x_values, mean, std_dev)
plt.plot(x_values, y_values, label=f'N({mean}, {std_dev}^2)')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(mean, color='red', linestyle='dashed', linewidth=1)
plt.title('Normal Distribution')
plt.xlabel('x')
plt.