Fix mypy errors for arithmetic analysis algorithms (#4053)

This commit is contained in:
Dhruv Manilawala 2020-12-23 15:22:43 +05:30 committed by GitHub
parent 2ff2ccbeec
commit ad5108d6a4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 90 additions and 60 deletions

View File

@ -1,19 +1,14 @@
""" """
Checks if a system of forces is in static equilibrium. Checks if a system of forces is in static equilibrium.
python/black : true
flake8 : passed
mypy : passed
""" """
from typing import List
from __future__ import annotations from numpy import array, cos, cross, radians, sin
from numpy import array, cos, cross, radians, sin # type: ignore
def polar_force( def polar_force(
magnitude: float, angle: float, radian_mode: bool = False magnitude: float, angle: float, radian_mode: bool = False
) -> list[float]: ) -> List[float]:
""" """
Resolves force along rectangular components. Resolves force along rectangular components.
(force, angle) => (force_x, force_y) (force, angle) => (force_x, force_y)

View File

@ -1,34 +1,64 @@
"""Lower-Upper (LU) Decomposition.""" """Lower-Upper (LU) Decomposition.
# lowerupper (LU) decomposition - https://en.wikipedia.org/wiki/LU_decomposition Reference:
import numpy - https://en.wikipedia.org/wiki/LU_decomposition
"""
from typing import Tuple
import numpy as np
from numpy import ndarray
def LUDecompose(table): def lower_upper_decomposition(table: ndarray) -> Tuple[ndarray, ndarray]:
"""Lower-Upper (LU) Decomposition
Example:
>>> matrix = np.array([[2, -2, 1], [0, 1, 2], [5, 3, 1]])
>>> outcome = lower_upper_decomposition(matrix)
>>> outcome[0]
array([[1. , 0. , 0. ],
[0. , 1. , 0. ],
[2.5, 8. , 1. ]])
>>> outcome[1]
array([[ 2. , -2. , 1. ],
[ 0. , 1. , 2. ],
[ 0. , 0. , -17.5]])
>>> matrix = np.array([[2, -2, 1], [0, 1, 2]])
>>> lower_upper_decomposition(matrix)
Traceback (most recent call last):
...
ValueError: 'table' has to be of square shaped array but got a 2x3 array:
[[ 2 -2 1]
[ 0 1 2]]
"""
# Table that contains our data # Table that contains our data
# Table has to be a square array so we need to check first # Table has to be a square array so we need to check first
rows, columns = numpy.shape(table) rows, columns = np.shape(table)
L = numpy.zeros((rows, columns))
U = numpy.zeros((rows, columns))
if rows != columns: if rows != columns:
return [] 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 i in range(columns):
for j in range(i): for j in range(i):
sum = 0 total = 0
for k in range(j): for k in range(j):
sum += L[i][k] * U[k][j] total += lower[i][k] * upper[k][j]
L[i][j] = (table[i][j] - sum) / U[j][j] lower[i][j] = (table[i][j] - total) / upper[j][j]
L[i][i] = 1 lower[i][i] = 1
for j in range(i, columns): for j in range(i, columns):
sum1 = 0 total = 0
for k in range(i): for k in range(i):
sum1 += L[i][k] * U[k][j] total += lower[i][k] * upper[k][j]
U[i][j] = table[i][j] - sum1 upper[i][j] = table[i][j] - total
return L, U return lower, upper
if __name__ == "__main__": if __name__ == "__main__":
matrix = numpy.array([[2, -2, 1], [0, 1, 2], [5, 3, 1]]) import doctest
L, U = LUDecompose(matrix)
print(L) doctest.testmod()
print(U)

View File

@ -1,10 +1,11 @@
# https://www.geeksforgeeks.org/newton-forward-backward-interpolation/ # https://www.geeksforgeeks.org/newton-forward-backward-interpolation/
import math import math
from typing import List
# for calculating u value # for calculating u value
def ucal(u, p): def ucal(u: float, p: int) -> float:
""" """
>>> ucal(1, 2) >>> ucal(1, 2)
0 0
@ -19,9 +20,9 @@ def ucal(u, p):
return temp return temp
def main(): def main() -> None:
n = int(input("enter the numbers of values: ")) n = int(input("enter the numbers of values: "))
y = [] y: List[List[float]] = []
for i in range(n): for i in range(n):
y.append([]) y.append([])
for i in range(n): for i in range(n):

View File

@ -4,11 +4,14 @@
# quickly find a good approximation for the root of a real-valued function # quickly find a good approximation for the root of a real-valued function
from decimal import Decimal from decimal import Decimal
from math import * # noqa: F401, F403 from math import * # noqa: F401, F403
from typing import Union
from sympy import diff from sympy import diff
def newton_raphson(func: str, a: int, precision: int = 10 ** -10) -> float: def newton_raphson(
func: str, a: Union[float, Decimal], precision: float = 10 ** -10
) -> float:
"""Finds root from the point 'a' onwards by Newton-Raphson method """Finds root from the point 'a' onwards by Newton-Raphson method
>>> newton_raphson("sin(x)", 2) >>> newton_raphson("sin(x)", 2)
3.1415926536808043 3.1415926536808043

View File

@ -1,28 +1,29 @@
# Implementing Secant method in Python """
# Author: dimgrichr Implementing Secant method in Python
Author: dimgrichr
"""
from math import exp from math import exp
def f(x): def f(x: float) -> float:
""" """
>>> f(5) >>> f(5)
39.98652410600183 39.98652410600183
""" """
return 8 * x - 2 * exp(-x) return 8 * x - 2 * exp(-x)
def SecantMethod(lower_bound, upper_bound, repeats): def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float:
""" """
>>> SecantMethod(1, 3, 2) >>> secant_method(1, 3, 2)
0.2139409276214589 0.2139409276214589
""" """
x0 = lower_bound x0 = lower_bound
x1 = upper_bound x1 = upper_bound
for i in range(0, repeats): for i in range(0, repeats):
x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0)) x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0))
return x1 return x1
print(f"The solution is: {SecantMethod(1, 3, 2)}") if __name__ == "__main__":
print(f"Example: {secant_method(1, 3, 2) = }")