NU-CEM / Computational_Physics

https://nu-cem.github.io/Computational_Physics
MIT License
1 stars 4 forks source link

Add physics examples using the lambda function #13

Open wheelchairscienceguy opened 1 week ago

wheelchairscienceguy commented 1 week ago

Add some example problems using the lambda function: https://www.w3schools.com/python/python_lambda.asp

https://en.wikipedia.org/wiki/Anonymous_function

In the finite difference method section, the question about calculating the Laplacian of some function, you can define the function as a Lambda function:

import math

def integrand(x,y): return 6math.cos(x) + 7math.sin(y)

def laplacian(f_xy, x, y, h): return (f_xy(x+h,y) + f_xy(x-h,y) + f_xy(x,y+h) + f_xy(x,y-h) - 4*(f_xy(x,y))) / (h**2)

REPLACE IT WITH THE FOLLOWING FOR A NICER LOOKING FUNCTION:

import numpy as np

f_xy = lambda x, y: 6np.cos(x) + 7np.sin(y)

laplacian = lambda f_xy, x, y, h: (f_xy(x+h,y) + f_xy(x-h,y) + f_xy(x,y+h) + f_xy(x,y-h) - 4*(f_xy(x,y))) / (h**2)

lucydot commented 1 week ago

This is a really excellent idea @wheelchairscienceguy, thank you for suggesting this! One small adaptation to your idea is that I will keep the original code, as this relates to what was covered in the first-year course (defining functions) and then introduce the lambda function as a more concise alternative.

Thanks again, I'll incorporate now :)

lucydot commented 2 days ago

The website has been updated with a lambda function example. Thanks @wheelchairscienceguy !