function
stringlengths 18
3.86k
| intent_category
stringlengths 5
24
|
---|---|
def surface_area_cube(side_length: float) -> float:
if side_length < 0:
raise ValueError("surface_area_cube() only accepts non-negative values")
return 6 * side_length**2 | maths |
def surface_area_cuboid(length: float, breadth: float, height: float) -> float:
if length < 0 or breadth < 0 or height < 0:
raise ValueError("surface_area_cuboid() only accepts non-negative values")
return 2 * ((length * breadth) + (breadth * height) + (length * height)) | maths |
def surface_area_sphere(radius: float) -> float:
if radius < 0:
raise ValueError("surface_area_sphere() only accepts non-negative values")
return 4 * pi * radius**2 | maths |
def surface_area_hemisphere(radius: float) -> float:
if radius < 0:
raise ValueError("surface_area_hemisphere() only accepts non-negative values")
return 3 * pi * radius**2 | maths |
def surface_area_cone(radius: float, height: float) -> float:
if radius < 0 or height < 0:
raise ValueError("surface_area_cone() only accepts non-negative values")
return pi * radius * (radius + (height**2 + radius**2) ** 0.5) | maths |
def surface_area_conical_frustum(
radius_1: float, radius_2: float, height: float
) -> float:
if radius_1 < 0 or radius_2 < 0 or height < 0:
raise ValueError(
"surface_area_conical_frustum() only accepts non-negative values"
)
slant_height = (height**2 + (radius_1 - radius_2) ** 2) ** 0.5
return pi * ((slant_height * (radius_1 + radius_2)) + radius_1**2 + radius_2**2) | maths |
def surface_area_cylinder(radius: float, height: float) -> float:
if radius < 0 or height < 0:
raise ValueError("surface_area_cylinder() only accepts non-negative values")
return 2 * pi * radius * (height + radius) | maths |
def surface_area_torus(torus_radius: float, tube_radius: float) -> float:
if torus_radius < 0 or tube_radius < 0:
raise ValueError("surface_area_torus() only accepts non-negative values")
if torus_radius < tube_radius:
raise ValueError(
"surface_area_torus() does not support spindle or self intersecting tori"
)
return 4 * pow(pi, 2) * torus_radius * tube_radius | maths |
def area_rectangle(length: float, width: float) -> float:
if length < 0 or width < 0:
raise ValueError("area_rectangle() only accepts non-negative values")
return length * width | maths |
def area_square(side_length: float) -> float:
if side_length < 0:
raise ValueError("area_square() only accepts non-negative values")
return side_length**2 | maths |
def area_triangle(base: float, height: float) -> float:
if base < 0 or height < 0:
raise ValueError("area_triangle() only accepts non-negative values")
return (base * height) / 2 | maths |
def area_triangle_three_sides(side1: float, side2: float, side3: float) -> float:
if side1 < 0 or side2 < 0 or side3 < 0:
raise ValueError("area_triangle_three_sides() only accepts non-negative values")
elif side1 + side2 < side3 or side1 + side3 < side2 or side2 + side3 < side1:
raise ValueError("Given three sides do not form a triangle")
semi_perimeter = (side1 + side2 + side3) / 2
area = sqrt(
semi_perimeter
* (semi_perimeter - side1)
* (semi_perimeter - side2)
* (semi_perimeter - side3)
)
return area | maths |
def area_parallelogram(base: float, height: float) -> float:
if base < 0 or height < 0:
raise ValueError("area_parallelogram() only accepts non-negative values")
return base * height | maths |
def area_trapezium(base1: float, base2: float, height: float) -> float:
if base1 < 0 or base2 < 0 or height < 0:
raise ValueError("area_trapezium() only accepts non-negative values")
return 1 / 2 * (base1 + base2) * height | maths |
def area_circle(radius: float) -> float:
if radius < 0:
raise ValueError("area_circle() only accepts non-negative values")
return pi * radius**2 | maths |
def area_ellipse(radius_x: float, radius_y: float) -> float:
if radius_x < 0 or radius_y < 0:
raise ValueError("area_ellipse() only accepts non-negative values")
return pi * radius_x * radius_y | maths |
def area_rhombus(diagonal_1: float, diagonal_2: float) -> float:
if diagonal_1 < 0 or diagonal_2 < 0:
raise ValueError("area_rhombus() only accepts non-negative values")
return 1 / 2 * diagonal_1 * diagonal_2 | maths |
def area_reg_polygon(sides: int, length: float) -> float:
if not isinstance(sides, int) or sides < 3:
raise ValueError(
"area_reg_polygon() only accepts integers greater than or \ | maths |
def is_ip_v4_address_valid(ip_v4_address: str) -> bool:
octets = [int(i) for i in ip_v4_address.split(".") if i.isdigit()]
return len(octets) == 4 and all(0 <= int(octet) <= 254 for octet in octets) | maths |
def juggler_sequence(number: int) -> list[int]:
if not isinstance(number, int):
raise TypeError(f"Input value of [number={number}] must be an integer")
if number < 1:
raise ValueError(f"Input value of [number={number}] must be a positive integer")
sequence = [number]
while number != 1:
if number % 2 == 0:
number = math.floor(math.sqrt(number))
else:
number = math.floor(
math.sqrt(number) * math.sqrt(number) * math.sqrt(number)
)
sequence.append(number)
return sequence | maths |
def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
steps: int = 100,
) -> float:
x1 = x_start
fx1 = fnc(x_start)
area = 0.0
for _ in range(steps):
# Approximates small segments of curve as linear and solve
# for trapezoidal area
x2 = (x_end - x_start) / steps + x1
fx2 = fnc(x2)
area += abs(fx2 + fx1) * (x2 - x1) / 2
# Increment step
x1 = x2
fx1 = fx2
return area | maths |
def f(x):
return x**3 | maths |
def find_minimum_change(denominations: list[int], value: str) -> list[int]:
total_value = int(value)
# Initialize Result
answer = []
# Traverse through all denomination
for denomination in reversed(denominations):
# Find denominations
while int(total_value) >= int(denomination):
total_value -= int(denomination)
answer.append(denomination) # Append the "answers" array
return answer | maths |
def softmax(vector):
# Calculate e^x for each x in your vector where e is Euler's
# number (approximately 2.718)
exponent_vector = np.exp(vector)
# Add up the all the exponentials
sum_of_exponents = np.sum(exponent_vector)
# Divide every exponent by the sum of all exponents
softmax_vector = exponent_vector / sum_of_exponents
return softmax_vector | maths |
def time_func(func, *args, **kwargs):
start = time()
output = func(*args, **kwargs)
end = time()
if int(end - start) > 0:
print(f"{func.__name__} runtime: {(end - start):0.4f} s")
else:
print(f"{func.__name__} runtime: {(end - start) * 1000:0.4f} ms")
return output | maths |
def fib_iterative(n: int) -> list[int]:
if n < 0:
raise Exception("n is negative")
if n == 0:
return [0]
fib = [0, 1]
for _ in range(n - 1):
fib.append(fib[-1] + fib[-2])
return fib | maths |
def fib_recursive_term(i: int) -> int:
if i < 0:
raise Exception("n is negative")
if i < 2:
return i
return fib_recursive_term(i - 1) + fib_recursive_term(i - 2) | maths |
def fib_recursive_term(i: int) -> int:
if i < 0:
raise Exception("n is negative")
if i < 2:
return i
return fib_recursive_term(i - 1) + fib_recursive_term(i - 2) | maths |
def rec_fn_memoized(num: int) -> int:
if num in cache:
return cache[num]
value = rec_fn_memoized(num - 1) + rec_fn_memoized(num - 2)
cache[num] = value
return value | maths |
def fib_binet(n: int) -> list[int]:
if n < 0:
raise Exception("n is negative")
if n >= 1475:
raise Exception("n is too large")
sqrt_5 = sqrt(5)
phi = (1 + sqrt_5) / 2
return [round(phi**i / sqrt_5) for i in range(n + 1)] | maths |
def aliquot_sum(input_num: int) -> int:
if not isinstance(input_num, int):
raise ValueError("Input must be an integer")
if input_num <= 0:
raise ValueError("Input must be positive")
return sum(
divisor for divisor in range(1, input_num // 2 + 1) if input_num % divisor == 0
) | maths |
def two_sum(nums: list[int], target: int) -> list[int]:
chk_map: dict[int, int] = {}
for index, val in enumerate(nums):
compl = target - val
if compl in chk_map:
return [chk_map[compl], index]
chk_map[val] = index
return [] | maths |
def sum_of_digits(n: int) -> int:
n = abs(n)
res = 0
while n > 0:
res += n % 10
n //= 10
return res | maths |
def sum_of_digits_recursion(n: int) -> int:
n = abs(n)
return n if n < 10 else n % 10 + sum_of_digits(n // 10) | maths |
def sum_of_digits_compact(n: int) -> int:
return sum(int(c) for c in str(abs(n))) | maths |
def benchmark_a_function(func: Callable, value: int) -> None:
call = f"{func.__name__}({value})"
timing = timeit(f"__main__.{call}", setup="import __main__")
print(f"{call:56} = {func(value)} -- {timing:.4f} seconds") | maths |
def prime_sieve(num: int) -> list[int]:
if num <= 0:
raise ValueError(f"{num}: Invalid input, please enter a positive integer.")
sieve = [True] * (num + 1)
prime = []
start = 2
end = int(math.sqrt(num))
while start <= end:
# If start is a prime
if sieve[start] is True:
prime.append(start)
# Set multiples of start be False
for i in range(start * start, num + 1, start):
if sieve[i] is True:
sieve[i] = False
start += 1
for j in range(end + 1, num + 1):
if sieve[j] is True:
prime.append(j)
return prime | maths |
def calculate_prob(text: str) -> None:
single_char_strings, two_char_strings = analyze_text(text)
my_alphas = list(" " + ascii_lowercase)
# what is our total sum of probabilities.
all_sum = sum(single_char_strings.values())
# one length string
my_fir_sum = 0
# for each alpha we go in our dict and if it is in it we calculate entropy
for ch in my_alphas:
if ch in single_char_strings:
my_str = single_char_strings[ch]
prob = my_str / all_sum
my_fir_sum += prob * math.log2(prob) # entropy formula.
# print entropy
print(f"{round(-1 * my_fir_sum):.1f}")
# two len string
all_sum = sum(two_char_strings.values())
my_sec_sum = 0
# for each alpha (two in size) calculate entropy.
for ch0 in my_alphas:
for ch1 in my_alphas:
sequence = ch0 + ch1
if sequence in two_char_strings:
my_str = two_char_strings[sequence]
prob = int(my_str) / all_sum
my_sec_sum += prob * math.log2(prob)
# print second entropy
print(f"{round(-1 * my_sec_sum):.1f}")
# print the difference between them
print(f"{round((-1 * my_sec_sum) - (-1 * my_fir_sum)):.1f}") | maths |
def analyze_text(text: str) -> tuple[dict, dict]:
single_char_strings = Counter() # type: ignore
two_char_strings = Counter() # type: ignore
single_char_strings[text[-1]] += 1
# first case when we have space at start.
two_char_strings[" " + text[0]] += 1
for i in range(0, len(text) - 1):
single_char_strings[text[i]] += 1
two_char_strings[text[i : i + 2]] += 1
return single_char_strings, two_char_strings | maths |
def main():
import doctest
doctest.testmod()
# text = (
# "Had repulsive dashwoods suspicion sincerity but advantage now him. Remark "
# "easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest "
# "jointure saw horrible. He private he on be imagine suppose. Fertile "
# "beloved evident through no service elderly is. Blind there if every no so "
# "at. Own neglected you preferred way sincerity delivered his attempted. To "
# "of message cottage windows do besides against uncivil. Delightful "
# "unreserved impossible few estimating men favourable see entreaties. She "
# "propriety immediate was improving. He or entrance humoured likewise "
# "moderate. Much nor game son say feel. Fat make met can must form into "
# "gate. Me we offending prevailed discovery. "
# )
# calculate_prob(text) | maths |
def num_digits(n: int) -> int:
digits = 0
n = abs(n)
while True:
n = n // 10
digits += 1
if n == 0:
break
return digits | maths |
def num_digits_fast(n: int) -> int:
return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1) | maths |
def num_digits_faster(n: int) -> int:
return len(str(abs(n))) | maths |
def benchmark_a_function(func: Callable, value: int) -> None:
call = f"{func.__name__}({value})"
timing = timeit(f"__main__.{call}", setup="import __main__")
print(f"{call}: {func(value)} -- {timing} seconds") | maths |
def gaussian(x, mu: float = 0.0, sigma: float = 1.0) -> int:
return 1 / sqrt(2 * pi * sigma**2) * exp(-((x - mu) ** 2) / (2 * sigma**2)) | maths |
def perfect_cube(n: int) -> bool:
val = n ** (1 / 3)
return (val * val * val) == n | maths |
def median(nums: list) -> int | float:
sorted_list = sorted(nums)
length = len(sorted_list)
mid_index = length >> 1
return (
(sorted_list[mid_index] + sorted_list[mid_index - 1]) / 2
if length % 2 == 0
else sorted_list[mid_index]
) | maths |
def main():
import doctest
doctest.testmod() | maths |
def mode(input_list: list) -> list[Any]:
if not input_list:
return []
result = [input_list.count(value) for value in input_list]
y = max(result) # Gets the maximum count in the input list.
# Gets values of modes
return sorted({input_list[i] for i, value in enumerate(result) if value == y}) | maths |
def is_automorphic_number(number: int) -> bool:
if not isinstance(number, int):
raise TypeError(f"Input value of [number={number}] must be an integer")
if number < 0:
return False
number_square = number * number
while number > 0:
if number % 10 != number_square % 10:
return False
number //= 10
number_square //= 10
return True | maths |
def radians(degree: float) -> float:
return degree / (180 / pi) | maths |
def collatz_sequence(n: int) -> list[int]:
if not isinstance(n, int) or n < 1:
raise Exception("Sequence only defined for natural numbers")
sequence = [n]
while n != 1:
n = 3 * n + 1 if n & 1 else n // 2
sequence.append(n)
return sequence | maths |
def main():
n = 43
sequence = collatz_sequence(n)
print(sequence)
print(f"collatz sequence from {n} took {len(sequence)} steps.") | maths |
def gamma(num: float) -> float:
if num <= 0:
raise ValueError("math domain error")
return quad(integrand, 0, inf, args=(num))[0] | maths |
def integrand(x: float, z: float) -> float:
return math.pow(x, z - 1) * math.exp(-x) | maths |
def sin(
angle_in_degrees: float, accuracy: int = 18, rounded_values_count: int = 10
) -> float:
# Simplify the angle to be between 360 and -360 degrees.
angle_in_degrees = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0)
# Converting from degrees to radians
angle_in_radians = radians(angle_in_degrees)
result = angle_in_radians
a = 3
b = -1
for _ in range(accuracy):
result += (b * (angle_in_radians**a)) / factorial(a)
b = -b # One positive term and the next will be negative and so on...
a += 2 # Increased by 2 for every term.
return round(result, rounded_values_count) | maths |
def mean(nums: list) -> float:
if not nums:
raise ValueError("List is empty")
return sum(nums) / len(nums) | maths |
def arc_length(angle: int, radius: int) -> float:
return 2 * pi * radius * (angle / 360) | maths |
def res(x, y):
if 0 not in (x, y):
# We use the relation x^y = y*log10(x), where 10 is the base.
return y * math.log10(x)
else:
if x == 0: # 0 raised to any number is 0
return 0
elif y == 0:
return 1 # any number raised to 0 is 1
raise AssertionError("This should never happen") | maths |
def equation(x: float) -> float:
return 10 - x * x | maths |
def bisection(a: float, b: float) -> float:
# Bolzano theory in order to find if there is a root between a and b
if equation(a) * equation(b) >= 0:
raise ValueError("Wrong space!")
c = a
while (b - a) >= 0.01:
# Find middle point
c = (a + b) / 2
# Check if middle point is root
if equation(c) == 0.0:
break
# Decide the side to repeat the steps
if equation(c) * equation(a) < 0:
b = c
else:
a = c
return c | maths |
def is_arithmetic_series(series: list) -> bool:
if not isinstance(series, list):
raise ValueError("Input series is not valid, valid series - [2, 4, 6]")
if len(series) == 0:
raise ValueError("Input list must be a non empty list")
if len(series) == 1:
return True
common_diff = series[1] - series[0]
for index in range(len(series) - 1):
if series[index + 1] - series[index] != common_diff:
return False
return True | maths |
def arithmetic_mean(series: list) -> float:
if not isinstance(series, list):
raise ValueError("Input series is not valid, valid series - [2, 4, 6]")
if len(series) == 0:
raise ValueError("Input list must be a non empty list")
answer = 0
for val in series:
answer += val
return answer / len(series) | maths |
def is_geometric_series(series: list) -> bool:
if not isinstance(series, list):
raise ValueError("Input series is not valid, valid series - [2, 4, 8]")
if len(series) == 0:
raise ValueError("Input list must be a non empty list")
if len(series) == 1:
return True
try:
common_ratio = series[1] / series[0]
for index in range(len(series) - 1):
if series[index + 1] / series[index] != common_ratio:
return False
except ZeroDivisionError:
return False
return True | maths |
def geometric_mean(series: list) -> float:
if not isinstance(series, list):
raise ValueError("Input series is not valid, valid series - [2, 4, 8]")
if len(series) == 0:
raise ValueError("Input list must be a non empty list")
answer = 1
for value in series:
answer *= value
return pow(answer, 1 / len(series)) | maths |
def hexagonal_numbers(length: int) -> list[int]:
if length <= 0 or not isinstance(length, int):
raise ValueError("Length must be a positive integer.")
return [n * (2 * n - 1) for n in range(length)] | maths |
def geometric_series(
nth_term: float | int,
start_term_a: float | int,
common_ratio_r: float | int,
) -> list[float | int]:
if not all((nth_term, start_term_a, common_ratio_r)):
return []
series: list[float | int] = []
power = 1
multiple = common_ratio_r
for _ in range(int(nth_term)):
if not series:
series.append(start_term_a)
else:
power += 1
series.append(float(start_term_a * multiple))
multiple = pow(float(common_ratio_r), power)
return series | maths |
def harmonic_series(n_term: str) -> list:
if n_term == "":
return []
series: list = []
for temp in range(int(n_term)):
series.append(f"1/{temp + 1}" if series else "1")
return series | maths |
def p_series(nth_term: int | float | str, power: int | float | str) -> list[str]:
if nth_term == "":
return [""]
nth_term = int(nth_term)
power = int(power)
series: list[str] = []
for temp in range(int(nth_term)):
series.append(f"1 / {pow(temp + 1, int(power))}" if series else "1")
return series | maths |
def is_harmonic_series(series: list) -> bool:
if not isinstance(series, list):
raise ValueError("Input series is not valid, valid series - [1, 2/3, 2]")
if len(series) == 0:
raise ValueError("Input list must be a non empty list")
if len(series) == 1 and series[0] != 0:
return True
rec_series = []
series_len = len(series)
for i in range(0, series_len):
if series[i] == 0:
raise ValueError("Input series cannot have 0 as an element")
rec_series.append(1 / series[i])
common_diff = rec_series[1] - rec_series[0]
for index in range(2, series_len):
if rec_series[index] - rec_series[index - 1] != common_diff:
return False
return True | maths |
def harmonic_mean(series: list) -> float:
if not isinstance(series, list):
raise ValueError("Input series is not valid, valid series - [2, 4, 6]")
if len(series) == 0:
raise ValueError("Input list must be a non empty list")
answer = 0
for val in series:
answer += 1 / val
return len(series) / answer | maths |
def __init__(self, degree: int, coefficients: MutableSequence[float]) -> None:
if len(coefficients) != degree + 1:
raise ValueError(
"The number of coefficients should be equal to the degree + 1."
)
self.coefficients: list[float] = list(coefficients)
self.degree = degree | maths |
def __add__(self, polynomial_2: Polynomial) -> Polynomial:
if self.degree > polynomial_2.degree:
coefficients = self.coefficients[:]
for i in range(polynomial_2.degree + 1):
coefficients[i] += polynomial_2.coefficients[i]
return Polynomial(self.degree, coefficients)
else:
coefficients = polynomial_2.coefficients[:]
for i in range(self.degree + 1):
coefficients[i] += self.coefficients[i]
return Polynomial(polynomial_2.degree, coefficients) | maths |
def __sub__(self, polynomial_2: Polynomial) -> Polynomial:
return self + polynomial_2 * Polynomial(0, [-1]) | maths |
def __neg__(self) -> Polynomial:
return Polynomial(self.degree, [-c for c in self.coefficients]) | maths |
def __mul__(self, polynomial_2: Polynomial) -> Polynomial:
coefficients: list[float] = [0] * (self.degree + polynomial_2.degree + 1)
for i in range(self.degree + 1):
for j in range(polynomial_2.degree + 1):
coefficients[i + j] += (
self.coefficients[i] * polynomial_2.coefficients[j]
)
return Polynomial(self.degree + polynomial_2.degree, coefficients) | maths |
def evaluate(self, substitution: int | float) -> int | float:
result: int | float = 0
for i in range(self.degree + 1):
result += self.coefficients[i] * (substitution**i)
return result | maths |
def __str__(self) -> str:
polynomial = ""
for i in range(self.degree, -1, -1):
if self.coefficients[i] == 0:
continue
elif self.coefficients[i] > 0:
if polynomial:
polynomial += " + "
else:
polynomial += " - "
if i == 0:
polynomial += str(abs(self.coefficients[i]))
elif i == 1:
polynomial += str(abs(self.coefficients[i])) + "x"
else:
polynomial += str(abs(self.coefficients[i])) + "x^" + str(i)
return polynomial | maths |
def __repr__(self) -> str:
return self.__str__() | maths |
def derivative(self) -> Polynomial:
coefficients: list[float] = [0] * self.degree
for i in range(self.degree):
coefficients[i] = self.coefficients[i + 1] * (i + 1)
return Polynomial(self.degree - 1, coefficients) | maths |
def integral(self, constant: int | float = 0) -> Polynomial:
coefficients: list[float] = [0] * (self.degree + 2)
coefficients[0] = constant
for i in range(self.degree + 1):
coefficients[i + 1] = self.coefficients[i] / (i + 1)
return Polynomial(self.degree + 1, coefficients) | maths |
def __eq__(self, polynomial_2: object) -> bool:
if not isinstance(polynomial_2, Polynomial):
return False
if self.degree != polynomial_2.degree:
return False
for i in range(self.degree + 1):
if self.coefficients[i] != polynomial_2.coefficients[i]:
return False
return True | maths |
def f(x: float) -> float:
return 8 * x - 2 * exp(-x) | arithmetic_analysis |
def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float:
x0 = lower_bound
x1 = upper_bound
for _ in range(0, repeats):
x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0))
return x1 | arithmetic_analysis |
def jacobi_iteration_method(
coefficient_matrix: NDArray[float64],
constant_matrix: NDArray[float64],
init_val: list[int],
iterations: int,
) -> list[float]:
rows1, cols1 = coefficient_matrix.shape
rows2, cols2 = constant_matrix.shape
if rows1 != cols1:
raise ValueError(
f"Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}"
)
if cols2 != 1:
raise ValueError(f"Constant matrix must be nx1 but received {rows2}x{cols2}")
if rows1 != rows2:
raise ValueError(
)
if len(init_val) != rows1:
raise ValueError(
)
if iterations <= 0:
raise ValueError("Iterations must be at least 1")
table: NDArray[float64] = np.concatenate(
(coefficient_matrix, constant_matrix), axis=1
)
rows, cols = table.shape
strictly_diagonally_dominant(table)
# Iterates the whole matrix for given number of times
for _ in range(iterations):
new_val = []
for row in range(rows):
temp = 0
for col in range(cols):
if col == row:
denom = table[row][col]
elif col == cols - 1:
val = table[row][col]
else:
temp += (-1) * table[row][col] * init_val[col]
temp = (temp + val) / denom
new_val.append(temp)
init_val = new_val
return [float(i) for i in new_val] | arithmetic_analysis |
def strictly_diagonally_dominant(table: NDArray[float64]) -> bool:
rows, cols = table.shape
is_diagonally_dominant = True
for i in range(0, rows):
total = 0
for j in range(0, cols - 1):
if i == j:
continue
else:
total += table[i][j]
if table[i][i] <= total:
raise ValueError("Coefficient matrix is not strictly diagonally dominant")
return is_diagonally_dominant | arithmetic_analysis |
def polar_force(
magnitude: float, angle: float, radian_mode: bool = False
) -> list[float]:
if radian_mode:
return [magnitude * cos(angle), magnitude * sin(angle)]
return [magnitude * cos(radians(angle)), magnitude * sin(radians(angle))] | arithmetic_analysis |
def in_static_equilibrium(
forces: NDArray[float64], location: NDArray[float64], eps: float = 10**-1
) -> bool:
# summation of moments is zero
moments: NDArray[float64] = cross(location, forces)
sum_moments: float = sum(moments)
return abs(sum_moments) < eps | arithmetic_analysis |
def ucal(u: float, p: int) -> float:
temp = u
for i in range(1, p):
temp = temp * (u - i)
return temp | arithmetic_analysis |
def main() -> None:
n = int(input("enter the numbers of values: "))
y: list[list[float]] = []
for _ in range(n):
y.append([])
for i in range(n):
for j in range(n):
y[i].append(j)
y[i][j] = 0
print("enter the values of parameters in a list: ")
x = list(map(int, input().split()))
print("enter the values of corresponding parameters: ")
for i in range(n):
y[i][0] = float(input())
value = int(input("enter the value to interpolate: "))
u = (value - x[0]) / (x[1] - x[0])
# for calculating forward difference table
for i in range(1, n):
for j in range(n - i):
y[j][i] = y[j + 1][i - 1] - y[j][i - 1]
summ = y[0][0]
for i in range(1, n):
summ += (ucal(u, i) * y[0][i]) / math.factorial(i)
print(f"the value at {value} is {summ}") | arithmetic_analysis |
def newton_raphson(
func: str, a: float | Decimal, precision: float = 10**-10
) -> float:
x = a
while True:
x = Decimal(x) - (Decimal(eval(func)) / Decimal(eval(str(diff(func)))))
# This number dictates the accuracy of the answer
if abs(eval(func)) < precision:
return float(x) | arithmetic_analysis |
def retroactive_resolution(
coefficients: NDArray[float64], vector: NDArray[float64]
) -> NDArray[float64]:
rows, columns = np.shape(coefficients)
x: NDArray[float64] = np.zeros((rows, 1), dtype=float)
for row in reversed(range(rows)):
total = 0
for col in range(row + 1, columns):
total += coefficients[row, col] * x[col]
x[row, 0] = (vector[row] - total) / coefficients[row, row]
return x | arithmetic_analysis |
def gaussian_elimination(
coefficients: NDArray[float64], vector: NDArray[float64]
) -> NDArray[float64]:
# coefficients must to be a square matrix so we need to check first
rows, columns = np.shape(coefficients)
if rows != columns:
return np.array((), dtype=float)
# augmented matrix
augmented_mat: NDArray[float64] = np.concatenate((coefficients, vector), axis=1)
augmented_mat = augmented_mat.astype("float64")
# scale the matrix leaving it triangular
for row in range(rows - 1):
pivot = augmented_mat[row, row]
for col in range(row + 1, columns):
factor = augmented_mat[col, row] / pivot
augmented_mat[col, :] -= factor * augmented_mat[row, :]
x = retroactive_resolution(
augmented_mat[:, 0:columns], augmented_mat[:, columns : columns + 1]
)
return x | arithmetic_analysis |
def newton_raphson(
function: str,
starting_point: complex,
variable: str = "x",
precision: float = 10**-10,
multiplicity: int = 1,
) -> complex:
x = symbols(variable)
func = lambdify(x, function)
diff_function = lambdify(x, diff(function, x))
prev_guess = starting_point
while True:
if diff_function(prev_guess) != 0:
next_guess = prev_guess - multiplicity * func(prev_guess) / diff_function(
prev_guess
)
else:
raise ZeroDivisionError("Could not find root") from None
# Precision is checked by comparing the difference of consecutive guesses
if abs(next_guess - prev_guess) < precision:
return next_guess
prev_guess = next_guess | arithmetic_analysis |
def intersection(function: Callable[[float], float], x0: float, x1: float) -> float:
x_n: float = x0
x_n1: float = x1
while True:
if x_n == x_n1 or function(x_n1) == function(x_n):
raise ZeroDivisionError("float division by zero, could not find root")
x_n2: float = x_n1 - (
function(x_n1) / ((function(x_n1) - function(x_n)) / (x_n1 - x_n))
)
if abs(x_n2 - x_n1) < 10**-5:
return x_n2
x_n = x_n1
x_n1 = x_n2 | arithmetic_analysis |
def f(x: float) -> float:
return math.pow(x, 3) - (2 * x) - 5 | arithmetic_analysis |
def lower_upper_decomposition(
table: ArrayLike[float64],
) -> tuple[ArrayLike[float64], ArrayLike[float64]]:
# Table that contains our data
# Table has to be a square array so we need to check first
rows, columns = np.shape(table)
if rows != columns:
raise ValueError(
f"'table' has to be of square shaped array but got a {rows}x{columns} "
+ f"array:\n{table}"
)
lower = np.zeros((rows, columns))
upper = np.zeros((rows, columns))
for i in range(columns):
for j in range(i):
total = 0
for k in range(j):
total += lower[i][k] * upper[k][j]
lower[i][j] = (table[i][j] - total) / upper[j][j]
lower[i][i] = 1
for j in range(i, columns):
total = 0
for k in range(i):
total += lower[i][k] * upper[k][j]
upper[i][j] = table[i][j] - total
return lower, upper | arithmetic_analysis |
def bisection(function: Callable[[float], float], a: float, b: float) -> float:
start: float = a
end: float = b
if function(a) == 0: # one of the a or b is a root for the function
return a
elif function(b) == 0:
return b
elif (
function(a) * function(b) > 0
): # if none of these are root and they are both positive or negative,
# then this algorithm can't find the root
raise ValueError("could not find root in given interval.")
else:
mid: float = start + (end - start) / 2.0
while abs(start - mid) > 10**-7: # until precisely equals to 10^-7
if function(mid) == 0:
return mid
elif function(mid) * function(start) < 0:
end = mid
else:
start = mid
mid = start + (end - start) / 2.0
return mid | arithmetic_analysis |
def f(x: float) -> float:
return x**3 - 2 * x - 5 | arithmetic_analysis |
def lamberts_ellipsoidal_distance(
lat1: float, lon1: float, lat2: float, lon2: float
) -> float:
# CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System
# Distance in metres(m)
# Equation Parameters
# https://en.wikipedia.org/wiki/Geographical_distance#Lambert's_formula_for_long_lines
flattening = (AXIS_A - AXIS_B) / AXIS_A
# Parametric latitudes
# https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude
b_lat1 = atan((1 - flattening) * tan(radians(lat1)))
b_lat2 = atan((1 - flattening) * tan(radians(lat2)))
# Compute central angle between two points
# using haversine theta. sigma = haversine_distance / equatorial radius
sigma = haversine_distance(lat1, lon1, lat2, lon2) / EQUATORIAL_RADIUS
# Intermediate P and Q values
p_value = (b_lat1 + b_lat2) / 2
q_value = (b_lat2 - b_lat1) / 2
# Intermediate X value
# X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2)
x_numerator = (sin(p_value) ** 2) * (cos(q_value) ** 2)
x_demonimator = cos(sigma / 2) ** 2
x_value = (sigma - sin(sigma)) * (x_numerator / x_demonimator)
# Intermediate Y value
# Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2)
y_numerator = (cos(p_value) ** 2) * (sin(q_value) ** 2)
y_denominator = sin(sigma / 2) ** 2
y_value = (sigma + sin(sigma)) * (y_numerator / y_denominator)
return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) | geodesy |