Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions problem_set/Q2_Chinese_Zodiac.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,29 @@

# write a function that takes the year as the input and produces the Zodiac for that year
# output should be in the format "2000 is the year of the Fire Rat"
chinese_dict= {
'animals': ["Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"],
'elements': ["Fire", "Earth", "Metal", "Water", "Wood"]
}
year=2000
def chinese_new_year(x):
"""
With an inputted year, the function will determine the CHinese Zodiac associated with that year
in a initialized cycle.
"""
x = int(x)
year = (x-2024) % 60
result=[]
for element in chinese_dict["elements"]:
for animal in chinese_dict["animals"]:
order = f"{element} {animal}"
result.append(order)
Zodiac = result[year]
if x<2024:
Messege = f"{x} was the year of the {Zodiac}"
else:
Messege = f"{x} is the year of the {Zodiac}"
return Messege

Zodiac = chinese_new_year(input("Input a year to determine it's associated Zodiac: "))
print(Zodiac)
86 changes: 80 additions & 6 deletions problem_set/Q3_Newton_Raphson_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,98 @@

# Use this root finding method to evaluate the square root of 2 to 6 decimal places

# The square root of 2 is 1.414213
# The square root of 2 is 1.414213 or 1.4142135623730951

true_value = 1.414213

import math
# compare your answer with the true value

# Define the function whose root we are trying to find


### write comments and code here ###
## Tool 1
def function_x(x):
"""
Define the Parent Function
"""
y= x**2 - 2
return y
# print(newton_rahpson(math.pi/2))


# Define the derivative of the function
# def RootstoQuadratic(x1,x2):
# """
# Using the knowledge of what a factored Quadratic looks like: x1,x2 = x² -x(x1+x2) + x1*x2.
# We can descrivbe a quadratic equation for any two inputted roots (in the Real plane).
# a = 1 because the value of c may compensate for the distances between the roots.
# (I hope to fix the issue and optimize for using a so that the value of c doesn't erupt.)
# """
# a= 1
# b= -(x1+x2)
# c= (x1*x2)
# equation = f"x² "
# if b == 0:
# equation = f"x² "
# else:
# if b < 0:
# equation += f"- {-b}x "
# else:
# equation += f"+ {b}x "

# if c < 0:
# equation += f"- {-c}"
# else:
# equation += f"+ {c}"
# if c == 0:
# equation = f"x²"
# print(f"The equation for these roots is: {equation}")
# return a,b,c
# a,b,c = RootstoQuadratic((3/2),6)

### write comments and code here ###
# # Define the derivative of the function

# ### write comments and code here ###
# ## Tool 2

def derivative_of_f(x):
"""
Define the derivative of the parent function
"""
y_prime= 2*(x)
return y_prime


# """
# We have an advantage because we always know we are dealing with a quadratic.
# It will be: 2x -(x1 + x2)
# """
# def QuadraticDerivative(b):
# if b != 0:
# if b < 0:
# print(f"The derivative is: 2x - {-b}")
# else:
# print(f"The derivative is: 2x + {b}")
# else:
# print("The derivative is: 2x")
# return b
# QuadraticDerivative(b)


# Run the algorithm for the necessary amount of iterations to converge to 6 d.p. accuracy, make sure to start with a good initial guess
# # Run the algorithm for the necessary amount of iterations to converge to 6 d.p. accuracy, make sure to start with a good initial guess
# ## Newton_Raphson_method
## xn+1 = xn - f(x)/f'(x)

def newton_rahpson(guess: int):
"""
This function uses a parent and derivative to approximate a root given an initial guess.
It is specified to a certain error.
"""
y = 1
while abs(y) > .000001:
next_guess = guess - (function_x(guess)/derivative_of_f(guess))
guess=next_guess
y = function_x(next_guess)
return next_guess

print(newton_rahpson(5))
print(f"True Value: {true_value}")
30 changes: 30 additions & 0 deletions problem_set/Q4_prime_number.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,33 @@
# Do not use a naive approach of checking every single number below
# At the least, do not check even numbers

def prime_number_solver(number):
"""
This function takes an input number and tests if it's prime or composite.
Outputs True or False respectfully.
"""
divisor = 3
sqrt_number = number**.5
compute = 0
#check if even: num % 2 == 0
if number == 1:
print("1 is neither prime nor composite!")
return None
elif number == 2:
print("2 is a prime number!")
return False
else:
if number % 2 == 0:
print(f"{number} is composite! It is even!")
return False
while divisor <= sqrt_number:
compute = number % divisor
if compute == 0:
print(f"{number} is composite! It failed with {divisor}.")
return False
divisor += 2
else:
print(f"{number} is prime!")
return True
x = prime_number_solver(number)
print(x)
34 changes: 32 additions & 2 deletions problem_set/Q5_taylor_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,35 @@
# Use numpy and matplotlib to plot your results and display them in the colour blue

# plot the real value of f(x) = sin(x) on the same plot in the colour red
#
#

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

def Taylor_Series(x):
"""
This funciton takes an input (x) with a defined taylor series function (in this case sin(x)).
It outputs a value, y, after summing a specified range of the series (n).
"""
sum=0
for n in range(0,11):
y = ((-1)**n * x**(2*n+1))/(math.factorial(2*n+1))
sum += y
return sum

x_range = np.arange(-2*math.pi,2*math.pi,.1) ## Makes the x range for the plot
output1 = [] ## Initial list for our taylor series function
for i in x_range:
y = Taylor_Series(i) ##Iterates through taylor series with the defined domain
output1.append(y)
y_range1 = np.array(output1) ##This is the y range for the taylor approximation in an array format to plot
y_range2 = np.sin(x_range) ##This is the second graph of the true sin(x) function to compare with Taylor

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 5)) ##This creates space for 2 plots##

ax1.plot(y_range1, color = 'blue') ##First plot of Taylor Approximation sin(x)

ax2.plot(y_range2, color = 'red')##Second plot of true sin(x)

plt.tight_layout()##formatting function
plt.show()