repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/__init__.py
maths/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/lucas_series.py
maths/lucas_series.py
""" https://en.wikipedia.org/wiki/Lucas_number """ def recursive_lucas_number(n_th_number: int) -> int: """ Returns the nth lucas number >>> recursive_lucas_number(1) 1 >>> recursive_lucas_number(20) 15127 >>> recursive_lucas_number(0) 2 >>> recursive_lucas_number(25) 167761 >>> recursive_lucas_number(-1.5) Traceback (most recent call last): ... TypeError: recursive_lucas_number accepts only integer arguments. """ if not isinstance(n_th_number, int): raise TypeError("recursive_lucas_number accepts only integer arguments.") if n_th_number == 0: return 2 if n_th_number == 1: return 1 return recursive_lucas_number(n_th_number - 1) + recursive_lucas_number( n_th_number - 2 ) def dynamic_lucas_number(n_th_number: int) -> int: """ Returns the nth lucas number >>> dynamic_lucas_number(1) 1 >>> dynamic_lucas_number(20) 15127 >>> dynamic_lucas_number(0) 2 >>> dynamic_lucas_number(25) 167761 >>> dynamic_lucas_number(-1.5) Traceback (most recent call last): ... TypeError: dynamic_lucas_number accepts only integer arguments. """ if not isinstance(n_th_number, int): raise TypeError("dynamic_lucas_number accepts only integer arguments.") a, b = 2, 1 for _ in range(n_th_number): a, b = b, a + b return a if __name__ == "__main__": from doctest import testmod testmod() n = int(input("Enter the number of terms in lucas series:\n").strip()) print("Using recursive function to calculate lucas series:") print(" ".join(str(recursive_lucas_number(i)) for i in range(n))) print("\nUsing dynamic function to calculate lucas series:") print(" ".join(str(dynamic_lucas_number(i)) for i in range(n)))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/karatsuba.py
maths/karatsuba.py
"""Multiply two numbers using Karatsuba algorithm""" def karatsuba(a: int, b: int) -> int: """ >>> karatsuba(15463, 23489) == 15463 * 23489 True >>> karatsuba(3, 9) == 3 * 9 True """ if len(str(a)) == 1 or len(str(b)) == 1: return a * b m1 = max(len(str(a)), len(str(b))) m2 = m1 // 2 a1, a2 = divmod(a, 10**m2) b1, b2 = divmod(b, 10**m2) x = karatsuba(a2, b2) y = karatsuba((a1 + a2), (b1 + b2)) z = karatsuba(a1, b1) return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x) def main(): print(karatsuba(15463, 23489)) if __name__ == "__main__": main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/chebyshev_distance.py
maths/chebyshev_distance.py
def chebyshev_distance(point_a: list[float], point_b: list[float]) -> float: """ This function calculates the Chebyshev distance (also known as the Chessboard distance) between two n-dimensional points represented as lists. https://en.wikipedia.org/wiki/Chebyshev_distance >>> chebyshev_distance([1.0, 1.0], [2.0, 2.0]) 1.0 >>> chebyshev_distance([1.0, 1.0, 9.0], [2.0, 2.0, -5.2]) 14.2 >>> chebyshev_distance([1.0], [2.0, 2.0]) Traceback (most recent call last): ... ValueError: Both points must have the same dimension. """ if len(point_a) != len(point_b): raise ValueError("Both points must have the same dimension.") return max(abs(a - b) for a, b in zip(point_a, point_b))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/combinations.py
maths/combinations.py
""" https://en.wikipedia.org/wiki/Combination """ def combinations(n: int, k: int) -> int: """ Returns the number of different combinations of k length which can be made from n values, where n >= k. Examples: >>> combinations(10,5) 252 >>> combinations(6,3) 20 >>> combinations(20,5) 15504 >>> combinations(52, 5) 2598960 >>> combinations(0, 0) 1 >>> combinations(-4, -5) ... Traceback (most recent call last): ValueError: Please enter positive integers for n and k where n >= k """ # If either of the conditions are true, the function is being asked # to calculate a factorial of a negative number, which is not possible if n < k or k < 0: raise ValueError("Please enter positive integers for n and k where n >= k") res = 1 for i in range(k): res *= n - i res //= i + 1 return res if __name__ == "__main__": print( "The number of five-card hands possible from a standard", f"fifty-two card deck is: {combinations(52, 5)}\n", ) print( "If a class of 40 students must be arranged into groups of", f"4 for group projects, there are {combinations(40, 4)} ways", "to arrange them.\n", ) print( "If 10 teams are competing in a Formula One race, there", f"are {combinations(10, 3)} ways that first, second and", "third place can be awarded.", )
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/quadratic_equations_complex_numbers.py
maths/quadratic_equations_complex_numbers.py
from __future__ import annotations from cmath import sqrt def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]: """ Given the numerical coefficients a, b and c, calculates the roots for any quadratic equation of the form ax^2 + bx + c >>> quadratic_roots(a=1, b=3, c=-4) (1.0, -4.0) >>> quadratic_roots(5, 6, 1) (-0.2, -1.0) >>> quadratic_roots(1, -6, 25) ((3+4j), (3-4j)) """ if a == 0: raise ValueError("Coefficient 'a' must not be zero.") delta = b * b - 4 * a * c root_1 = (-b + sqrt(delta)) / (2 * a) root_2 = (-b - sqrt(delta)) / (2 * a) return ( root_1.real if not root_1.imag else root_1, root_2.real if not root_2.imag else root_2, ) def main(): solution1, solution2 = quadratic_roots(a=5, b=6, c=1) print(f"The solutions are: {solution1} and {solution2}") if __name__ == "__main__": main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/aliquot_sum.py
maths/aliquot_sum.py
def aliquot_sum(input_num: int) -> int: """ Finds the aliquot sum of an input integer, where the aliquot sum of a number n is defined as the sum of all natural numbers less than n that divide n evenly. For example, the aliquot sum of 15 is 1 + 3 + 5 = 9. This is a simple O(n) implementation. @param input_num: a positive integer whose aliquot sum is to be found @return: the aliquot sum of input_num, if input_num is positive. Otherwise, raise a ValueError Wikipedia Explanation: https://en.wikipedia.org/wiki/Aliquot_sum >>> aliquot_sum(15) 9 >>> aliquot_sum(6) 6 >>> aliquot_sum(-1) Traceback (most recent call last): ... ValueError: Input must be positive >>> aliquot_sum(0) Traceback (most recent call last): ... ValueError: Input must be positive >>> aliquot_sum(1.6) Traceback (most recent call last): ... ValueError: Input must be an integer >>> aliquot_sum(12) 16 >>> aliquot_sum(1) 0 >>> aliquot_sum(19) 1 """ 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 ) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/fast_inverse_sqrt.py
maths/fast_inverse_sqrt.py
""" Fast inverse square root (1/sqrt(x)) using the Quake III algorithm. Reference: https://en.wikipedia.org/wiki/Fast_inverse_square_root Accuracy: https://en.wikipedia.org/wiki/Fast_inverse_square_root#Accuracy """ import struct def fast_inverse_sqrt(number: float) -> float: """ Compute the fast inverse square root of a floating-point number using the famous Quake III algorithm. :param float number: Input number for which to calculate the inverse square root. :return float: The fast inverse square root of the input number. Example: >>> fast_inverse_sqrt(10) 0.3156857923527257 >>> fast_inverse_sqrt(4) 0.49915357479239103 >>> fast_inverse_sqrt(4.1) 0.4932849504615651 >>> fast_inverse_sqrt(0) Traceback (most recent call last): ... ValueError: Input must be a positive number. >>> fast_inverse_sqrt(-1) Traceback (most recent call last): ... ValueError: Input must be a positive number. >>> from math import isclose, sqrt >>> all(isclose(fast_inverse_sqrt(i), 1 / sqrt(i), rel_tol=0.00132) ... for i in range(50, 60)) True """ if number <= 0: raise ValueError("Input must be a positive number.") i = struct.unpack(">i", struct.pack(">f", number))[0] i = 0x5F3759DF - (i >> 1) y = struct.unpack(">f", struct.pack(">i", i))[0] return y * (1.5 - 0.5 * number * y * y) if __name__ == "__main__": from doctest import testmod testmod() # https://en.wikipedia.org/wiki/Fast_inverse_square_root#Accuracy from math import sqrt for i in range(5, 101, 5): print(f"{i:>3}: {(1 / sqrt(i)) - fast_inverse_sqrt(i):.5f}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/juggler_sequence.py
maths/juggler_sequence.py
""" == Juggler Sequence == Juggler sequence start with any positive integer n. The next term is obtained as follows: If n term is even, the next term is floor value of square root of n . If n is odd, the next term is floor value of 3 time the square root of n. https://en.wikipedia.org/wiki/Juggler_sequence """ # Author : Akshay Dubey (https://github.com/itsAkshayDubey) import math def juggler_sequence(number: int) -> list[int]: """ >>> juggler_sequence(0) Traceback (most recent call last): ... ValueError: Input value of [number=0] must be a positive integer >>> juggler_sequence(1) [1] >>> juggler_sequence(2) [2, 1] >>> juggler_sequence(3) [3, 5, 11, 36, 6, 2, 1] >>> juggler_sequence(5) [5, 11, 36, 6, 2, 1] >>> juggler_sequence(10) [10, 3, 5, 11, 36, 6, 2, 1] >>> juggler_sequence(25) [25, 125, 1397, 52214, 228, 15, 58, 7, 18, 4, 2, 1] >>> juggler_sequence(6.0) Traceback (most recent call last): ... TypeError: Input value of [number=6.0] must be an integer >>> juggler_sequence(-1) Traceback (most recent call last): ... ValueError: Input value of [number=-1] must be a positive integer """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: msg = f"Input value of [number={number}] must be a positive integer" raise ValueError(msg) 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 if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/greatest_common_divisor.py
maths/greatest_common_divisor.py
""" Greatest Common Divisor. Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor gcd(a, b) = gcd(a, -b) = gcd(-a, b) = gcd(-a, -b) by definition of divisibility """ def greatest_common_divisor(a: int, b: int) -> int: """ Calculate Greatest Common Divisor (GCD). >>> greatest_common_divisor(24, 40) 8 >>> greatest_common_divisor(1, 1) 1 >>> greatest_common_divisor(1, 800) 1 >>> greatest_common_divisor(11, 37) 1 >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(16, 4) 4 >>> greatest_common_divisor(-3, 9) 3 >>> greatest_common_divisor(9, -3) 3 >>> greatest_common_divisor(3, -9) 3 >>> greatest_common_divisor(-3, -9) 3 """ return abs(b) if a == 0 else greatest_common_divisor(b % a, a) def gcd_by_iterative(x: int, y: int) -> int: """ Below method is more memory efficient because it does not create additional stack frames for recursive functions calls (as done in the above method). >>> gcd_by_iterative(24, 40) 8 >>> greatest_common_divisor(24, 40) == gcd_by_iterative(24, 40) True >>> gcd_by_iterative(-3, -9) 3 >>> gcd_by_iterative(3, -9) 3 >>> gcd_by_iterative(1, -800) 1 >>> gcd_by_iterative(11, 37) 1 """ while y: # --> when y=0 then loop will terminate and return x as final GCD. x, y = y, x % y return abs(x) def main(): """ Call Greatest Common Divisor function. """ try: nums = input("Enter two integers separated by comma (,): ").split(",") num_1 = int(nums[0]) num_2 = int(nums[1]) print( f"greatest_common_divisor({num_1}, {num_2}) = " f"{greatest_common_divisor(num_1, num_2)}" ) print(f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}") except (IndexError, UnboundLocalError, ValueError): print("Wrong input") if __name__ == "__main__": main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/sum_of_arithmetic_series.py
maths/sum_of_arithmetic_series.py
# DarkCoder def sum_of_series(first_term: int, common_diff: int, num_of_terms: int) -> float: """ Find the sum of n terms in an arithmetic progression. >>> sum_of_series(1, 1, 10) 55.0 >>> sum_of_series(1, 10, 100) 49600.0 """ total = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def main(): print(sum_of_series(1, 1, 10)) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/test_prime_check.py
maths/test_prime_check.py
""" Minimalist file that allows pytest to find and run the Test unittest. For details, see: https://doc.pytest.org/en/latest/goodpractices.html#conventions-for-python-test-discovery """ from .prime_check import Test Test()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/is_ip_v4_address_valid.py
maths/is_ip_v4_address_valid.py
""" wiki: https://en.wikipedia.org/wiki/IPv4 Is IP v4 address valid? A valid IP address must be four octets in the form of A.B.C.D, where A, B, C and D are numbers from 0-255 for example: 192.168.23.1, 172.255.255.255 are valid IP address 192.168.256.0, 256.192.3.121 are invalid IP address """ def is_ip_v4_address_valid(ip: str) -> bool: """ print "Valid IP address" If IP is valid. or print "Invalid IP address" If IP is invalid. >>> is_ip_v4_address_valid("192.168.0.23") True >>> is_ip_v4_address_valid("192.256.15.8") False >>> is_ip_v4_address_valid("172.100.0.8") True >>> is_ip_v4_address_valid("255.256.0.256") False >>> is_ip_v4_address_valid("1.2.33333333.4") False >>> is_ip_v4_address_valid("1.2.-3.4") False >>> is_ip_v4_address_valid("1.2.3") False >>> is_ip_v4_address_valid("1.2.3.4.5") False >>> is_ip_v4_address_valid("1.2.A.4") False >>> is_ip_v4_address_valid("0.0.0.0") True >>> is_ip_v4_address_valid("1.2.3.") False >>> is_ip_v4_address_valid("1.2.3.05") False """ octets = ip.split(".") if len(octets) != 4: return False for octet in octets: if not octet.isdigit(): return False number = int(octet) if len(str(number)) != len(octet): return False if not 0 <= number <= 255: return False return True if __name__ == "__main__": ip = input().strip() valid_or_invalid = "valid" if is_ip_v4_address_valid(ip) else "invalid" print(f"{ip} is a {valid_or_invalid} IPv4 address.")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/decimal_to_fraction.py
maths/decimal_to_fraction.py
def decimal_to_fraction(decimal: float | str) -> tuple[int, int]: """ Return a decimal number in its simplest fraction form >>> decimal_to_fraction(2) (2, 1) >>> decimal_to_fraction(89.) (89, 1) >>> decimal_to_fraction("67") (67, 1) >>> decimal_to_fraction("45.0") (45, 1) >>> decimal_to_fraction(1.5) (3, 2) >>> decimal_to_fraction("6.25") (25, 4) >>> decimal_to_fraction("78td") Traceback (most recent call last): ValueError: Please enter a valid number >>> decimal_to_fraction(0) (0, 1) >>> decimal_to_fraction(-2.5) (-5, 2) >>> decimal_to_fraction(0.125) (1, 8) >>> decimal_to_fraction(1000000.25) (4000001, 4) >>> decimal_to_fraction(1.3333) (13333, 10000) >>> decimal_to_fraction("1.23e2") (123, 1) >>> decimal_to_fraction("0.500") (1, 2) """ try: decimal = float(decimal) except ValueError: raise ValueError("Please enter a valid number") fractional_part = decimal - int(decimal) if fractional_part == 0: return int(decimal), 1 else: number_of_frac_digits = len(str(decimal).split(".")[1]) numerator = int(decimal * (10**number_of_frac_digits)) denominator = 10**number_of_frac_digits divisor, dividend = denominator, numerator while True: remainder = dividend % divisor if remainder == 0: break dividend, divisor = divisor, remainder numerator, denominator = numerator // divisor, denominator // divisor return numerator, denominator if __name__ == "__main__": print(f"{decimal_to_fraction(2) = }") print(f"{decimal_to_fraction(89.0) = }") print(f"{decimal_to_fraction('67') = }") print(f"{decimal_to_fraction('45.0') = }") print(f"{decimal_to_fraction(1.5) = }") print(f"{decimal_to_fraction('6.25') = }") print(f"{decimal_to_fraction('78td') = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/maclaurin_series.py
maths/maclaurin_series.py
""" https://en.wikipedia.org/wiki/Taylor_series#Trigonometric_functions """ from math import factorial, pi def maclaurin_sin(theta: float, accuracy: int = 30) -> float: """ Finds the maclaurin approximation of sin :param theta: the angle to which sin is found :param accuracy: the degree of accuracy wanted minimum :return: the value of sine in radians >>> from math import isclose, sin >>> all(isclose(maclaurin_sin(x, 50), sin(x)) for x in range(-25, 25)) True >>> maclaurin_sin(10) -0.5440211108893691 >>> maclaurin_sin(-10) 0.5440211108893704 >>> maclaurin_sin(10, 15) -0.544021110889369 >>> maclaurin_sin(-10, 15) 0.5440211108893704 >>> maclaurin_sin("10") Traceback (most recent call last): ... ValueError: maclaurin_sin() requires either an int or float for theta >>> maclaurin_sin(10, -30) Traceback (most recent call last): ... ValueError: maclaurin_sin() requires a positive int for accuracy >>> maclaurin_sin(10, 30.5) Traceback (most recent call last): ... ValueError: maclaurin_sin() requires a positive int for accuracy >>> maclaurin_sin(10, "30") Traceback (most recent call last): ... ValueError: maclaurin_sin() requires a positive int for accuracy """ if not isinstance(theta, (int, float)): raise ValueError("maclaurin_sin() requires either an int or float for theta") if not isinstance(accuracy, int) or accuracy <= 0: raise ValueError("maclaurin_sin() requires a positive int for accuracy") theta = float(theta) div = theta // (2 * pi) theta -= 2 * div * pi return sum( (-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1) for r in range(accuracy) ) def maclaurin_cos(theta: float, accuracy: int = 30) -> float: """ Finds the maclaurin approximation of cos :param theta: the angle to which cos is found :param accuracy: the degree of accuracy wanted :return: the value of cosine in radians >>> from math import isclose, cos >>> all(isclose(maclaurin_cos(x, 50), cos(x)) for x in range(-25, 25)) True >>> maclaurin_cos(5) 0.2836621854632268 >>> maclaurin_cos(-5) 0.2836621854632265 >>> maclaurin_cos(10, 15) -0.8390715290764524 >>> maclaurin_cos(-10, 15) -0.8390715290764521 >>> maclaurin_cos("10") Traceback (most recent call last): ... ValueError: maclaurin_cos() requires either an int or float for theta >>> maclaurin_cos(10, -30) Traceback (most recent call last): ... ValueError: maclaurin_cos() requires a positive int for accuracy >>> maclaurin_cos(10, 30.5) Traceback (most recent call last): ... ValueError: maclaurin_cos() requires a positive int for accuracy >>> maclaurin_cos(10, "30") Traceback (most recent call last): ... ValueError: maclaurin_cos() requires a positive int for accuracy """ if not isinstance(theta, (int, float)): raise ValueError("maclaurin_cos() requires either an int or float for theta") if not isinstance(accuracy, int) or accuracy <= 0: raise ValueError("maclaurin_cos() requires a positive int for accuracy") theta = float(theta) div = theta // (2 * pi) theta -= 2 * div * pi return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r) for r in range(accuracy)) if __name__ == "__main__": import doctest doctest.testmod() print(maclaurin_sin(10)) print(maclaurin_sin(-10)) print(maclaurin_sin(10, 15)) print(maclaurin_sin(-10, 15)) print(maclaurin_cos(5)) print(maclaurin_cos(-5)) print(maclaurin_cos(10, 15)) print(maclaurin_cos(-10, 15))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/sock_merchant.py
maths/sock_merchant.py
from collections import Counter def sock_merchant(colors: list[int]) -> int: """ >>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20]) 3 >>> sock_merchant([1, 1, 3, 3]) 2 """ return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values()) if __name__ == "__main__": import doctest doctest.testmod() colors = [int(x) for x in input("Enter socks by color :").rstrip().split()] print(f"sock_merchant({colors}) = {sock_merchant(colors)}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/arc_length.py
maths/arc_length.py
from math import pi def arc_length(angle: int, radius: int) -> float: """ >>> arc_length(45, 5) 3.9269908169872414 >>> arc_length(120, 15) 31.415926535897928 >>> arc_length(90, 10) 15.707963267948966 """ return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(90, 10))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/radians.py
maths/radians.py
from math import pi def radians(degree: float) -> float: """ Converts the given angle from degrees to radians https://en.wikipedia.org/wiki/Radian >>> radians(180) 3.141592653589793 >>> radians(92) 1.6057029118347832 >>> radians(274) 4.782202150464463 >>> radians(109.82) 1.9167205845401725 >>> from math import radians as math_radians >>> all(abs(radians(i) - math_radians(i)) <= 1e-8 for i in range(-2, 361)) True """ return degree / (180 / pi) if __name__ == "__main__": from doctest import testmod testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/double_factorial.py
maths/double_factorial.py
def double_factorial_recursive(n: int) -> int: """ Compute double factorial using recursive method. Recursion can be costly for large numbers. To learn about the theory behind this algorithm: https://en.wikipedia.org/wiki/Double_factorial >>> from math import prod >>> all(double_factorial_recursive(i) == prod(range(i, 0, -2)) for i in range(20)) True >>> double_factorial_recursive(0.1) Traceback (most recent call last): ... ValueError: double_factorial_recursive() only accepts integral values >>> double_factorial_recursive(-1) Traceback (most recent call last): ... ValueError: double_factorial_recursive() not defined for negative values """ if not isinstance(n, int): raise ValueError("double_factorial_recursive() only accepts integral values") if n < 0: raise ValueError("double_factorial_recursive() not defined for negative values") return 1 if n <= 1 else n * double_factorial_recursive(n - 2) def double_factorial_iterative(num: int) -> int: """ Compute double factorial using iterative method. To learn about the theory behind this algorithm: https://en.wikipedia.org/wiki/Double_factorial >>> from math import prod >>> all(double_factorial_iterative(i) == prod(range(i, 0, -2)) for i in range(20)) True >>> double_factorial_iterative(0.1) Traceback (most recent call last): ... ValueError: double_factorial_iterative() only accepts integral values >>> double_factorial_iterative(-1) Traceback (most recent call last): ... ValueError: double_factorial_iterative() not defined for negative values """ if not isinstance(num, int): raise ValueError("double_factorial_iterative() only accepts integral values") if num < 0: raise ValueError("double_factorial_iterative() not defined for negative values") value = 1 for i in range(num, 0, -2): value *= i return value if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/pollard_rho.py
maths/pollard_rho.py
from __future__ import annotations from math import gcd def pollard_rho( num: int, seed: int = 2, step: int = 1, attempts: int = 3, ) -> int | None: """ Use Pollard's Rho algorithm to return a nontrivial factor of ``num``. The returned factor may be composite and require further factorization. If the algorithm will return None if it fails to find a factor within the specified number of attempts or within the specified number of steps. If ``num`` is prime, this algorithm is guaranteed to return None. https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm >>> pollard_rho(18446744073709551617) 274177 >>> pollard_rho(97546105601219326301) 9876543191 >>> pollard_rho(100) 2 >>> pollard_rho(17) >>> pollard_rho(17**3) 17 >>> pollard_rho(17**3, attempts=1) >>> pollard_rho(3*5*7) 21 >>> pollard_rho(1) Traceback (most recent call last): ... ValueError: The input value cannot be less than 2 """ # A value less than 2 can cause an infinite loop in the algorithm. if num < 2: raise ValueError("The input value cannot be less than 2") # Because of the relationship between ``f(f(x))`` and ``f(x)``, this # algorithm struggles to find factors that are divisible by two. # As a workaround, we specifically check for two and even inputs. # See: https://math.stackexchange.com/a/2856214/165820 if num > 2 and num % 2 == 0: return 2 # Pollard's Rho algorithm requires a function that returns pseudorandom # values between 0 <= X < ``num``. It doesn't need to be random in the # sense that the output value is cryptographically secure or difficult # to calculate, it only needs to be random in the sense that all output # values should be equally likely to appear. # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num`` # However, the success of Pollard's algorithm isn't guaranteed and is # determined in part by the initial seed and the chosen random function. # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(value: int, step: int, modulus: int) -> int: """ Returns a pseudorandom value modulo ``modulus`` based on the input ``value`` and attempt-specific ``step`` size. >>> rand_fn(0, 0, 0) Traceback (most recent call last): ... ZeroDivisionError: integer division or modulo by zero >>> rand_fn(1, 2, 3) 0 >>> rand_fn(0, 10, 7) 3 >>> rand_fn(1234, 1, 17) 16 """ return (pow(value, 2) + step) % modulus for _ in range(attempts): # These track the position within the cycle detection logic. tortoise = seed hare = seed while True: # At each iteration, the tortoise moves one step and the hare moves two. tortoise = rand_fn(tortoise, step, num) hare = rand_fn(hare, step, num) hare = rand_fn(hare, step, num) # At some point both the tortoise and the hare will enter a cycle whose # length ``p`` is a divisor of ``num``. Once in that cycle, at some point # the tortoise and hare will end up on the same value modulo ``p``. # We can detect when this happens because the position difference between # the tortoise and the hare will share a common divisor with ``num``. divisor = gcd(hare - tortoise, num) if divisor == 1: # No common divisor yet, just keep searching. continue # We found a common divisor! elif divisor == num: # Unfortunately, the divisor is ``num`` itself and is useless. break else: # The divisor is a nontrivial factor of ``num``! return divisor # If we made it here, then this attempt failed. # We need to pick a new starting seed for the tortoise and hare # in addition to a new step value for the random function. # To keep this example implementation deterministic, the # new values will be generated based on currently available # values instead of using something like ``random.randint``. # We can use the hare's position as the new seed. # This is actually what Richard Brent's the "optimized" variant does. seed = hare # The new step value for the random function can just be incremented. # At first the results will be similar to what the old function would # have produced, but the value will quickly diverge after a bit. step += 1 # We haven't found a divisor within the requested number of attempts. # We were unlucky or ``num`` itself is actually prime. return None if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument( "num", type=int, help="The value to find a divisor of", ) parser.add_argument( "--attempts", type=int, default=3, help="The number of attempts before giving up", ) args = parser.parse_args() divisor = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(f"{args.num} is probably prime") else: quotient = args.num // divisor print(f"{args.num} = {divisor} * {quotient}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/addition_without_arithmetic.py
maths/addition_without_arithmetic.py
""" Illustrate how to add the integer without arithmetic operation Author: suraj Kumar Time Complexity: 1 https://en.wikipedia.org/wiki/Bitwise_operation """ def add(first: int, second: int) -> int: """ Implementation of addition of integer Examples: >>> add(3, 5) 8 >>> add(13, 5) 18 >>> add(-7, 2) -5 >>> add(0, -7) -7 >>> add(-321, 0) -321 """ while second != 0: c = first & second first ^= second second = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() first = int(input("Enter the first number: ").strip()) second = int(input("Enter the second number: ").strip()) print(f"{add(first, second) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/abs.py
maths/abs.py
"""Absolute Value.""" def abs_val(num: float) -> float: """ Find the absolute value of a number. >>> abs_val(-5.1) 5.1 >>> abs_val(-5) == abs_val(5) True >>> abs_val(0) 0 """ return -num if num < 0 else num def abs_min(x: list[int]) -> int: """ >>> abs_min([0,5,1,11]) 0 >>> abs_min([3,-10,-2]) -2 >>> abs_min([]) Traceback (most recent call last): ... ValueError: abs_min() arg is an empty sequence """ if len(x) == 0: raise ValueError("abs_min() arg is an empty sequence") j = x[0] for i in x: if abs_val(i) < abs_val(j): j = i return j def abs_max(x: list[int]) -> int: """ >>> abs_max([0,5,1,11]) 11 >>> abs_max([3,-10,-2]) -10 >>> abs_max([]) Traceback (most recent call last): ... ValueError: abs_max() arg is an empty sequence """ if len(x) == 0: raise ValueError("abs_max() arg is an empty sequence") j = x[0] for i in x: if abs(i) > abs(j): j = i return j def abs_max_sort(x: list[int]) -> int: """ >>> abs_max_sort([0,5,1,11]) 11 >>> abs_max_sort([3,-10,-2]) -10 >>> abs_max_sort([]) Traceback (most recent call last): ... ValueError: abs_max_sort() arg is an empty sequence """ if len(x) == 0: raise ValueError("abs_max_sort() arg is an empty sequence") return sorted(x, key=abs)[-1] def test_abs_val(): """ >>> test_abs_val() """ assert abs_val(0) == 0 assert abs_val(34) == 34 assert abs_val(-100000000000) == 100000000000 a = [-3, -1, 2, -11] assert abs_max(a) == -11 assert abs_max_sort(a) == -11 assert abs_min(a) == -1 if __name__ == "__main__": import doctest doctest.testmod() test_abs_val() print(abs_val(-34)) # --> 34
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/pi_generator.py
maths/pi_generator.py
def calculate_pi(limit: int) -> str: """ https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80 Leibniz Formula for Pi The Leibniz formula is the special case arctan(1) = pi / 4. Leibniz's formula converges extremely slowly: it exhibits sublinear convergence. Convergence (https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80#Convergence) We cannot try to prove against an interrupted, uncompleted generation. https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80#Unusual_behaviour The errors can in fact be predicted, but those calculations also approach infinity for accuracy. Our output will be a string so that we can definitely store all digits. >>> import math >>> float(calculate_pi(15)) == math.pi True Since we cannot predict errors or interrupt any infinite alternating series generation since they approach infinity, or interrupt any alternating series, we'll need math.isclose() >>> math.isclose(float(calculate_pi(50)), math.pi) True >>> math.isclose(float(calculate_pi(100)), math.pi) True Since math.pi contains only 16 digits, here are some tests with known values: >>> calculate_pi(50) '3.14159265358979323846264338327950288419716939937510' >>> calculate_pi(80) '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899' """ # Variables used for the iteration process q = 1 r = 0 t = 1 k = 1 n = 3 m = 3 decimal = limit counter = 0 result = "" # We can't compare against anything if we make a generator, # so we'll stick with plain return logic while counter != decimal + 1: if 4 * q + r - t < n * t: result += str(n) if counter == 0: result += "." if decimal == counter: break counter += 1 nr = 10 * (r - n * t) n = ((10 * (3 * q + r)) // t) - 10 * n q *= 10 r = nr else: nr = (2 * q + r) * m nn = (q * (7 * k) + 2 + (r * m)) // (t * m) q *= k t *= m m += 2 k += 1 n = nn r = nr return result def main() -> None: print(f"{calculate_pi(50) = }") import doctest doctest.testmod() if __name__ == "__main__": main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/binomial_coefficient.py
maths/binomial_coefficient.py
def binomial_coefficient(n: int, r: int) -> int: """ Find binomial coefficient using Pascal's triangle. Calculate C(n, r) using Pascal's triangle. :param n: The total number of items. :param r: The number of items to choose. :return: The binomial coefficient C(n, r). >>> binomial_coefficient(10, 5) 252 >>> binomial_coefficient(10, 0) 1 >>> binomial_coefficient(0, 10) 1 >>> binomial_coefficient(10, 10) 1 >>> binomial_coefficient(5, 2) 10 >>> binomial_coefficient(5, 6) 0 >>> binomial_coefficient(3, 5) 0 >>> binomial_coefficient(-2, 3) Traceback (most recent call last): ... ValueError: n and r must be non-negative integers >>> binomial_coefficient(5, -1) Traceback (most recent call last): ... ValueError: n and r must be non-negative integers >>> binomial_coefficient(10.1, 5) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> binomial_coefficient(10, 5.1) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer """ if n < 0 or r < 0: raise ValueError("n and r must be non-negative integers") if 0 in (n, r): return 1 c = [0 for i in range(r + 1)] # nc0 = 1 c[0] = 1 for i in range(1, n + 1): # to compute current row from previous row. j = min(i, r) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] if __name__ == "__main__": from doctest import testmod testmod() print(binomial_coefficient(n=10, r=5))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/chinese_remainder_theorem.py
maths/chinese_remainder_theorem.py
""" Chinese Remainder Theorem: GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) If GCD(a,b) = 1, then for any remainder ra modulo a and any remainder rb modulo b there exists integer n, such that n = ra (mod a) and n = ra(mod b). If n1 and n2 are two such integers, then n1=n2(mod ab) Algorithm : 1. Use extended euclid algorithm to find x,y such that a*x + b*y = 1 2. Take n = ra*by + rb*ax """ from __future__ import annotations # Extended Euclid def extended_euclid(a: int, b: int) -> tuple[int, int]: """ >>> extended_euclid(10, 6) (-1, 2) >>> extended_euclid(7, 5) (-2, 3) """ if b == 0: return (1, 0) (x, y) = extended_euclid(b, a % b) k = a // b return (y, x - k * y) # Uses ExtendedEuclid to find inverses def chinese_remainder_theorem(n1: int, r1: int, n2: int, r2: int) -> int: """ >>> chinese_remainder_theorem(5,1,7,3) 31 Explanation : 31 is the smallest number such that (i) When we divide it by 5, we get remainder 1 (ii) When we divide it by 7, we get remainder 3 >>> chinese_remainder_theorem(6,1,4,3) 14 """ (x, y) = extended_euclid(n1, n2) m = n1 * n2 n = r2 * x * n1 + r1 * y * n2 return (n % m + m) % m # ----------SAME SOLUTION USING InvertModulo instead ExtendedEuclid---------------- # This function find the inverses of a i.e., a^(-1) def invert_modulo(a: int, n: int) -> int: """ >>> invert_modulo(2, 5) 3 >>> invert_modulo(8,7) 1 """ (b, _x) = extended_euclid(a, n) if b < 0: b = (b % n + n) % n return b # Same a above using InvertingModulo def chinese_remainder_theorem2(n1: int, r1: int, n2: int, r2: int) -> int: """ >>> chinese_remainder_theorem2(5,1,7,3) 31 >>> chinese_remainder_theorem2(6,1,4,3) 14 """ x, y = invert_modulo(n1, n2), invert_modulo(n2, n1) m = n1 * n2 n = r2 * x * n1 + r1 * y * n2 return (n % m + m) % m if __name__ == "__main__": from doctest import testmod testmod(name="chinese_remainder_theorem", verbose=True) testmod(name="chinese_remainder_theorem2", verbose=True) testmod(name="invert_modulo", verbose=True) testmod(name="extended_euclid", verbose=True)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/two_pointer.py
maths/two_pointer.py
""" Given a sorted array of integers, return indices of the two numbers such that they add up to a specific target using the two pointers technique. You may assume that each input would have exactly one solution, and you may not use the same element twice. This is an alternative solution of the two-sum problem, which uses a map to solve the problem. Hence can not solve the issue if there is a constraint not use the same index twice. [1] Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. [1]: https://github.com/TheAlgorithms/Python/blob/master/other/two_sum.py """ from __future__ import annotations def two_pointer(nums: list[int], target: int) -> list[int]: """ >>> two_pointer([2, 7, 11, 15], 9) [0, 1] >>> two_pointer([2, 7, 11, 15], 17) [0, 3] >>> two_pointer([2, 7, 11, 15], 18) [1, 2] >>> two_pointer([2, 7, 11, 15], 26) [2, 3] >>> two_pointer([1, 3, 3], 6) [1, 2] >>> two_pointer([2, 7, 11, 15], 8) [] >>> two_pointer([3 * i for i in range(10)], 19) [] >>> two_pointer([1, 2, 3], 6) [] """ i = 0 j = len(nums) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: i = i + 1 else: j = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"{two_pointer([2, 7, 11, 15], 9) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/max_sum_sliding_window.py
maths/max_sum_sliding_window.py
""" Given an array of integer elements and an integer 'k', we are required to find the maximum sum of 'k' consecutive elements in the array. Instead of using a nested for loop, in a Brute force approach we will use a technique called 'Window sliding technique' where the nested loops can be converted to a single loop to reduce time complexity. """ from __future__ import annotations def max_sum_in_array(array: list[int], k: int) -> int: """ Returns the maximum sum of k consecutive elements >>> arr = [1, 4, 2, 10, 2, 3, 1, 0, 20] >>> k = 4 >>> max_sum_in_array(arr, k) 24 >>> k = 10 >>> max_sum_in_array(arr,k) Traceback (most recent call last): ... ValueError: Invalid Input >>> arr = [1, 4, 2, 10, 2, 13, 1, 0, 2] >>> k = 4 >>> max_sum_in_array(arr, k) 27 """ if len(array) < k or k < 0: raise ValueError("Invalid Input") max_sum = current_sum = sum(array[:k]) for i in range(len(array) - k): current_sum = current_sum - array[i] + array[i + k] max_sum = max(max_sum, current_sum) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() array = [randint(-1000, 1000) for i in range(100)] k = randint(0, 110) print( f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array, k)}" )
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/allocation_number.py
maths/allocation_number.py
""" In a multi-threaded download, this algorithm could be used to provide each worker thread with a block of non-overlapping bytes to download. For example: for i in allocation_list: requests.get(url,headers={'Range':f'bytes={i}'}) """ from __future__ import annotations def allocation_num(number_of_bytes: int, partitions: int) -> list[str]: """ Divide a number of bytes into x partitions. :param number_of_bytes: the total of bytes. :param partitions: the number of partition need to be allocated. :return: list of bytes to be assigned to each worker thread >>> allocation_num(16647, 4) ['1-4161', '4162-8322', '8323-12483', '12484-16647'] >>> allocation_num(50000, 5) ['1-10000', '10001-20000', '20001-30000', '30001-40000', '40001-50000'] >>> allocation_num(888, 999) Traceback (most recent call last): ... ValueError: partitions can not > number_of_bytes! >>> allocation_num(888, -4) Traceback (most recent call last): ... ValueError: partitions must be a positive number! """ if partitions <= 0: raise ValueError("partitions must be a positive number!") if partitions > number_of_bytes: raise ValueError("partitions can not > number_of_bytes!") bytes_per_partition = number_of_bytes // partitions allocation_list = [] for i in range(partitions): start_bytes = i * bytes_per_partition + 1 end_bytes = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f"{start_bytes}-{end_bytes}") return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/sin.py
maths/sin.py
""" Calculate sin function. It's not a perfect function so I am rounding the result to 10 decimal places by default. Formula: sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ... Where: x = angle in randians. Source: https://www.homeschoolmath.net/teaching/sine_calculator.php """ from math import factorial, radians def sin( angle_in_degrees: float, accuracy: int = 18, rounded_values_count: int = 10 ) -> float: """ Implement sin function. >>> sin(0.0) 0.0 >>> sin(90.0) 1.0 >>> sin(180.0) 0.0 >>> sin(270.0) -1.0 >>> sin(0.68) 0.0118679603 >>> sin(1.97) 0.0343762121 >>> sin(64.0) 0.8987940463 >>> sin(9999.0) -0.9876883406 >>> sin(-689.0) 0.5150380749 >>> sin(89.7) 0.9999862922 """ # 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) if __name__ == "__main__": __import__("doctest").testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/radix2_fft.py
maths/radix2_fft.py
""" Fast Polynomial Multiplication using radix-2 fast Fourier Transform. """ import mpmath # for roots of unity import numpy as np class FFT: """ Fast Polynomial Multiplication using radix-2 fast Fourier Transform. Reference: https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#The_radix-2_DIT_case For polynomials of degree m and n the algorithms has complexity O(n*logn + m*logm) The main part of the algorithm is split in two parts: 1) __DFT: We compute the discrete fourier transform (DFT) of A and B using a bottom-up dynamic approach - 2) __multiply: Once we obtain the DFT of A*B, we can similarly invert it to obtain A*B The class FFT takes two polynomials A and B with complex coefficients as arguments; The two polynomials should be represented as a sequence of coefficients starting from the free term. Thus, for instance x + 2*x^3 could be represented as [0,1,0,2] or (0,1,0,2). The constructor adds some zeros at the end so that the polynomials have the same length which is a power of 2 at least the length of their product. Example: Create two polynomials as sequences >>> A = [0, 1, 0, 2] # x+2x^3 >>> B = (2, 3, 4, 0) # 2+3x+4x^2 Create an FFT object with them >>> x = FFT(A, B) Print product >>> x.product # 2x + 3x^2 + 8x^3 + 6x^4 + 8x^5 [(-0-0j), (2+0j), (3-0j), (8-0j), (6+0j), (8+0j)] __str__ test >>> print(x) A = 0*x^0 + 1*x^1 + 0*x^2 + 2*x^3 B = 2*x^0 + 3*x^1 + 4*x^2 A*B = (-0-0j)*x^0 + (2+0j)*x^1 + (3-0j)*x^2 + (8-0j)*x^3 + (6+0j)*x^4 + (8+0j)*x^5 """ def __init__(self, poly_a=None, poly_b=None): # Input as list self.polyA = list(poly_a or [0])[:] self.polyB = list(poly_b or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() self.len_A = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() self.len_B = len(self.polyB) # Add 0 to make lengths equal a power of 2 self.c_max_length = int( 2 ** np.ceil(np.log2(len(self.polyA) + len(self.polyB) - 1)) ) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) # A complex root used for the fourier transform self.root = complex(mpmath.root(x=1, n=self.c_max_length, k=1)) # The product self.product = self.__multiply() # Discrete fourier transform of A and B def __dft(self, which): dft = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB] # Corner case if len(dft) <= 1: return dft[0] next_ncol = self.c_max_length // 2 while next_ncol > 0: new_dft = [[] for i in range(next_ncol)] root = self.root**next_ncol # First half of next step current_root = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step current_root = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update dft = new_dft next_ncol = next_ncol // 2 return dft[0] # multiply the DFTs of A and B and find A*B def __multiply(self): dft_a = self.__dft("A") dft_b = self.__dft("B") inverce_c = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT next_ncol = 2 while next_ncol <= self.c_max_length: new_inverse_c = [[] for i in range(next_ncol)] root = self.root ** (next_ncol // 2) current_root = 1 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2 ) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root) ) current_root *= root # Update inverce_c = new_inverse_c next_ncol *= 2 # Unpack inverce_c = [ complex(round(x[0].real, 8), round(x[0].imag, 8)) for x in inverce_c ] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c # Overwrite __str__ for print(); Shows A, B and A*B def __str__(self): a = "A = " + " + ".join( f"{coef}*x^{i}" for i, coef in enumerate(self.polyA[: self.len_A]) ) b = "B = " + " + ".join( f"{coef}*x^{i}" for i, coef in enumerate(self.polyB[: self.len_B]) ) c = "A*B = " + " + ".join( f"{coef}*x^{i}" for i, coef in enumerate(self.product) ) return f"{a}\n{b}\n{c}" # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/decimal_isolate.py
maths/decimal_isolate.py
""" Isolate the Decimal part of a Number https://stackoverflow.com/questions/3886402/how-to-get-numbers-after-decimal-point """ def decimal_isolate(number: float, digit_amount: int) -> float: """ Isolates the decimal part of a number. If digitAmount > 0 round to that decimal place, else print the entire decimal. >>> decimal_isolate(1.53, 0) 0.53 >>> decimal_isolate(35.345, 1) 0.3 >>> decimal_isolate(35.345, 2) 0.34 >>> decimal_isolate(35.345, 3) 0.345 >>> decimal_isolate(-14.789, 3) -0.789 >>> decimal_isolate(0, 2) 0 >>> decimal_isolate(-14.123, 1) -0.1 >>> decimal_isolate(-14.123, 2) -0.12 >>> decimal_isolate(-14.123, 3) -0.123 """ if digit_amount > 0: return round(number - int(number), digit_amount) return number - int(number) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/intersection.py
maths/numerical_analysis/intersection.py
import math from collections.abc import Callable def intersection(function: Callable[[float], float], x0: float, x1: float) -> float: """ function is the f we want to find its root x0 and x1 are two random starting points >>> intersection(lambda x: x ** 3 - 1, -5, 5) 0.9999999999954654 >>> intersection(lambda x: x ** 3 - 1, 5, 5) Traceback (most recent call last): ... ZeroDivisionError: float division by zero, could not find root >>> intersection(lambda x: x ** 3 - 1, 100, 200) 1.0000000000003888 >>> intersection(lambda x: x ** 2 - 4 * x + 3, 0, 2) 0.9999999998088019 >>> intersection(lambda x: x ** 2 - 4 * x + 3, 2, 4) 2.9999999998088023 >>> intersection(lambda x: x ** 2 - 4 * x + 3, 4, 1000) 3.0000000001786042 >>> intersection(math.sin, -math.pi, math.pi) 0.0 >>> intersection(math.cos, -math.pi, math.pi) Traceback (most recent call last): ... ZeroDivisionError: float division by zero, could not find root """ 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 def f(x: float) -> float: """ function is f(x) = x^3 - 2x - 5 >>> f(2) -1.0 """ return math.pow(x, 3) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/bisection.py
maths/numerical_analysis/bisection.py
from collections.abc import Callable def bisection(function: Callable[[float], float], a: float, b: float) -> float: """ finds where function becomes 0 in [a,b] using bolzano >>> bisection(lambda x: x ** 3 - 1, -5, 5) 1.0000000149011612 >>> bisection(lambda x: x ** 3 - 1, 2, 1000) Traceback (most recent call last): ... ValueError: could not find root in given interval. >>> bisection(lambda x: x ** 2 - 4 * x + 3, 0, 2) 1.0 >>> bisection(lambda x: x ** 2 - 4 * x + 3, 2, 4) 3.0 >>> bisection(lambda x: x ** 2 - 4 * x + 3, 4, 1000) Traceback (most recent call last): ... ValueError: could not find root in given interval. """ 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 def f(x: float) -> float: return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/numerical_integration.py
maths/numerical_analysis/numerical_integration.py
""" Approximates the area under the curve using the trapezoidal rule """ from __future__ import annotations from collections.abc import Callable def trapezoidal_area( fnc: Callable[[float], float], x_start: float, x_end: float, steps: int = 100, ) -> float: """ Treats curve as a collection of linear lines and sums the area of the trapezium shape they form :param fnc: a function which defines a curve :param x_start: left end point to indicate the start of line segment :param x_end: right end point to indicate end of line segment :param steps: an accuracy gauge; more steps increases the accuracy :return: a float representing the length of the curve >>> def f(x): ... return 5 >>> '%.3f' % trapezoidal_area(f, 12.0, 14.0, 1000) '10.000' >>> def f(x): ... return 9*x**2 >>> '%.4f' % trapezoidal_area(f, -4.0, 0, 10000) '192.0000' >>> '%.4f' % trapezoidal_area(f, -4.0, 4.0, 10000) '384.0000' """ 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 if __name__ == "__main__": def f(x): return x**3 print("f(x) = x^3") print("The area between the curve, x = -10, x = 10 and the x axis is:") i = 10 while i <= 100000: area = trapezoidal_area(f, -5, 5, i) print(f"with {i} steps: {area}") i *= 10
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/newton_forward_interpolation.py
maths/numerical_analysis/newton_forward_interpolation.py
# https://www.geeksforgeeks.org/newton-forward-backward-interpolation/ from __future__ import annotations import math # for calculating u value def ucal(u: float, p: int) -> float: """ >>> ucal(1, 2) 0 >>> ucal(1.1, 2) 0.11000000000000011 >>> ucal(1.2, 2) 0.23999999999999994 """ temp = u for i in range(1, p): temp = temp * (u - i) return temp 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}") if __name__ == "__main__": main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/newton_raphson.py
maths/numerical_analysis/newton_raphson.py
""" The Newton-Raphson method (aka the Newton method) is a root-finding algorithm that approximates a root of a given real-valued function f(x). It is an iterative method given by the formula x_{n + 1} = x_n + f(x_n) / f'(x_n) with the precision of the approximation increasing as the number of iterations increase. Reference: https://en.wikipedia.org/wiki/Newton%27s_method """ from collections.abc import Callable RealFunc = Callable[[float], float] def calc_derivative(f: RealFunc, x: float, delta_x: float = 1e-3) -> float: """ Approximate the derivative of a function f(x) at a point x using the finite difference method >>> import math >>> tolerance = 1e-5 >>> derivative = calc_derivative(lambda x: x**2, 2) >>> math.isclose(derivative, 4, abs_tol=tolerance) True >>> derivative = calc_derivative(math.sin, 0) >>> math.isclose(derivative, 1, abs_tol=tolerance) True """ return (f(x + delta_x / 2) - f(x - delta_x / 2)) / delta_x def newton_raphson( f: RealFunc, x0: float = 0, max_iter: int = 100, step: float = 1e-6, max_error: float = 1e-6, log_steps: bool = False, ) -> tuple[float, float, list[float]]: """ Find a root of the given function f using the Newton-Raphson method. :param f: A real-valued single-variable function :param x0: Initial guess :param max_iter: Maximum number of iterations :param step: Step size of x, used to approximate f'(x) :param max_error: Maximum approximation error :param log_steps: bool denoting whether to log intermediate steps :return: A tuple containing the approximation, the error, and the intermediate steps. If log_steps is False, then an empty list is returned for the third element of the tuple. :raises ZeroDivisionError: The derivative approaches 0. :raises ArithmeticError: No solution exists, or the solution isn't found before the iteration limit is reached. >>> import math >>> tolerance = 1e-15 >>> root, *_ = newton_raphson(lambda x: x**2 - 5*x + 2, 0.4, max_error=tolerance) >>> math.isclose(root, (5 - math.sqrt(17)) / 2, abs_tol=tolerance) True >>> root, *_ = newton_raphson(lambda x: math.log(x) - 1, 2, max_error=tolerance) >>> math.isclose(root, math.e, abs_tol=tolerance) True >>> root, *_ = newton_raphson(math.sin, 1, max_error=tolerance) >>> math.isclose(root, 0, abs_tol=tolerance) True >>> newton_raphson(math.cos, 0) Traceback (most recent call last): ... ZeroDivisionError: No converging solution found, zero derivative >>> newton_raphson(lambda x: x**2 + 1, 2) Traceback (most recent call last): ... ArithmeticError: No converging solution found, iteration limit reached """ def f_derivative(x: float) -> float: return calc_derivative(f, x, step) a = x0 # Set initial guess steps = [] for _ in range(max_iter): if log_steps: # Log intermediate steps steps.append(a) error = abs(f(a)) if error < max_error: return a, error, steps if f_derivative(a) == 0: raise ZeroDivisionError("No converging solution found, zero derivative") a -= f(a) / f_derivative(a) # Calculate next estimate raise ArithmeticError("No converging solution found, iteration limit reached") if __name__ == "__main__": import doctest from math import exp, tanh doctest.testmod() def func(x: float) -> float: return tanh(x) ** 2 - exp(3 * x) solution, err, steps = newton_raphson( func, x0=10, max_iter=100, step=1e-6, log_steps=True ) print(f"{solution=}, {err=}") print("\n".join(str(x) for x in steps))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/runge_kutta_fehlberg_45.py
maths/numerical_analysis/runge_kutta_fehlberg_45.py
""" Use the Runge-Kutta-Fehlberg method to solve Ordinary Differential Equations. """ from collections.abc import Callable import numpy as np def runge_kutta_fehlberg_45( func: Callable, x_initial: float, y_initial: float, step_size: float, x_final: float, ) -> np.ndarray: """ Solve an Ordinary Differential Equations using Runge-Kutta-Fehlberg Method (rkf45) of order 5. https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta%E2%80%93Fehlberg_method args: func: An ordinary differential equation (ODE) as function of x and y. x_initial: The initial value of x. y_initial: The initial value of y. step_size: The increment value of x. x_final: The final value of x. Returns: Solution of y at each nodal point # exact value of y[1] is tan(0.2) = 0.2027100937470787 >>> def f(x, y): ... return 1 + y**2 >>> y = runge_kutta_fehlberg_45(f, 0, 0, 0.2, 1) >>> float(y[1]) 0.2027100937470787 >>> def f(x,y): ... return x >>> y = runge_kutta_fehlberg_45(f, -1, 0, 0.2, 0) >>> float(y[1]) -0.18000000000000002 >>> y = runge_kutta_fehlberg_45(5, 0, 0, 0.1, 1) Traceback (most recent call last): ... TypeError: 'int' object is not callable >>> def f(x, y): ... return x + y >>> y = runge_kutta_fehlberg_45(f, 0, 0, 0.2, -1) Traceback (most recent call last): ... ValueError: The final value of x must be greater than initial value of x. >>> def f(x, y): ... return x >>> y = runge_kutta_fehlberg_45(f, -1, 0, -0.2, 0) Traceback (most recent call last): ... ValueError: Step size must be positive. """ if x_initial >= x_final: raise ValueError( "The final value of x must be greater than initial value of x." ) if step_size <= 0: raise ValueError("Step size must be positive.") n = int((x_final - x_initial) / step_size) y = np.zeros( (n + 1), ) x = np.zeros(n + 1) y[0] = y_initial x[0] = x_initial for i in range(n): k1 = step_size * func(x[i], y[i]) k2 = step_size * func(x[i] + step_size / 4, y[i] + k1 / 4) k3 = step_size * func( x[i] + (3 / 8) * step_size, y[i] + (3 / 32) * k1 + (9 / 32) * k2 ) k4 = step_size * func( x[i] + (12 / 13) * step_size, y[i] + (1932 / 2197) * k1 - (7200 / 2197) * k2 + (7296 / 2197) * k3, ) k5 = step_size * func( x[i] + step_size, y[i] + (439 / 216) * k1 - 8 * k2 + (3680 / 513) * k3 - (845 / 4104) * k4, ) k6 = step_size * func( x[i] + step_size / 2, y[i] - (8 / 27) * k1 + 2 * k2 - (3544 / 2565) * k3 + (1859 / 4104) * k4 - (11 / 40) * k5, ) y[i + 1] = ( y[i] + (16 / 135) * k1 + (6656 / 12825) * k3 + (28561 / 56430) * k4 - (9 / 50) * k5 + (2 / 55) * k6 ) x[i + 1] = step_size + x[i] return y if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/runge_kutta_gills.py
maths/numerical_analysis/runge_kutta_gills.py
""" Use the Runge-Kutta-Gill's method of order 4 to solve Ordinary Differential Equations. https://www.geeksforgeeks.org/gills-4th-order-method-to-solve-differential-equations/ Author : Ravi Kumar """ from collections.abc import Callable from math import sqrt import numpy as np def runge_kutta_gills( func: Callable[[float, float], float], x_initial: float, y_initial: float, step_size: float, x_final: float, ) -> np.ndarray: """ Solve an Ordinary Differential Equations using Runge-Kutta-Gills Method of order 4. args: func: An ordinary differential equation (ODE) as function of x and y. x_initial: The initial value of x. y_initial: The initial value of y. step_size: The increment value of x. x_final: The final value of x. Returns: Solution of y at each nodal point >>> def f(x, y): ... return (x-y)/2 >>> y = runge_kutta_gills(f, 0, 3, 0.2, 5) >>> float(y[-1]) 3.4104259225717537 >>> def f(x,y): ... return x >>> y = runge_kutta_gills(f, -1, 0, 0.2, 0) >>> y array([ 0. , -0.18, -0.32, -0.42, -0.48, -0.5 ]) >>> def f(x, y): ... return x + y >>> y = runge_kutta_gills(f, 0, 0, 0.2, -1) Traceback (most recent call last): ... ValueError: The final value of x must be greater than initial value of x. >>> def f(x, y): ... return x >>> y = runge_kutta_gills(f, -1, 0, -0.2, 0) Traceback (most recent call last): ... ValueError: Step size must be positive. """ if x_initial >= x_final: raise ValueError( "The final value of x must be greater than initial value of x." ) if step_size <= 0: raise ValueError("Step size must be positive.") n = int((x_final - x_initial) / step_size) y = np.zeros(n + 1) y[0] = y_initial for i in range(n): k1 = step_size * func(x_initial, y[i]) k2 = step_size * func(x_initial + step_size / 2, y[i] + k1 / 2) k3 = step_size * func( x_initial + step_size / 2, y[i] + (-0.5 + 1 / sqrt(2)) * k1 + (1 - 1 / sqrt(2)) * k2, ) k4 = step_size * func( x_initial + step_size, y[i] - (1 / sqrt(2)) * k2 + (1 + 1 / sqrt(2)) * k3 ) y[i + 1] = y[i] + (k1 + (2 - sqrt(2)) * k2 + (2 + sqrt(2)) * k3 + k4) / 6 x_initial += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/secant_method.py
maths/numerical_analysis/secant_method.py
""" Implementing Secant method in Python Author: dimgrichr """ from math import exp def f(x: float) -> float: """ >>> f(5) 39.98652410600183 """ return 8 * x - 2 * exp(-x) def secant_method(lower_bound: float, upper_bound: float, repeats: int) -> float: """ >>> secant_method(1, 3, 2) 0.2139409276214589 """ x0 = lower_bound x1 = upper_bound for _ in range(repeats): x0, x1 = x1, x1 - (f(x1) * (x1 - x0)) / (f(x1) - f(x0)) return x1 if __name__ == "__main__": print(f"Example: {secant_method(1, 3, 2)}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/adams_bashforth.py
maths/numerical_analysis/adams_bashforth.py
""" Use the Adams-Bashforth methods to solve Ordinary Differential Equations. https://en.wikipedia.org/wiki/Linear_multistep_method Author : Ravi Kumar """ from collections.abc import Callable from dataclasses import dataclass import numpy as np @dataclass class AdamsBashforth: """ args: func: An ordinary differential equation (ODE) as function of x and y. x_initials: List containing initial required values of x. y_initials: List containing initial required values of y. step_size: The increment value of x. x_final: The final value of x. Returns: Solution of y at each nodal point >>> def f(x, y): ... return x + y >>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0.2, 1], 0.2, 1) # doctest: +ELLIPSIS AdamsBashforth(func=..., x_initials=[0, 0.2, 0.4], y_initials=[0, 0.2, 1], step...) >>> AdamsBashforth(f, [0, 0.2, 1], [0, 0, 0.04], 0.2, 1).step_2() Traceback (most recent call last): ... ValueError: The final value of x must be greater than the initial values of x. >>> AdamsBashforth(f, [0, 0.2, 0.3], [0, 0, 0.04], 0.2, 1).step_3() Traceback (most recent call last): ... ValueError: x-values must be equally spaced according to step size. >>> AdamsBashforth(f,[0,0.2,0.4,0.6,0.8],[0,0,0.04,0.128,0.307],-0.2,1).step_5() Traceback (most recent call last): ... ValueError: Step size must be positive. """ func: Callable[[float, float], float] x_initials: list[float] y_initials: list[float] step_size: float x_final: float def __post_init__(self) -> None: if self.x_initials[-1] >= self.x_final: raise ValueError( "The final value of x must be greater than the initial values of x." ) if self.step_size <= 0: raise ValueError("Step size must be positive.") if not all( round(x1 - x0, 10) == self.step_size for x0, x1 in zip(self.x_initials, self.x_initials[1:]) ): raise ValueError("x-values must be equally spaced according to step size.") def step_2(self) -> np.ndarray: """ >>> def f(x, y): ... return x >>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_2() array([0. , 0. , 0.06, 0.16, 0.3 , 0.48]) >>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_2() Traceback (most recent call last): ... ValueError: Insufficient initial points information. """ if len(self.x_initials) != 2 or len(self.y_initials) != 2: raise ValueError("Insufficient initial points information.") x_0, x_1 = self.x_initials[:2] y_0, y_1 = self.y_initials[:2] n = int((self.x_final - x_1) / self.step_size) y = np.zeros(n + 2) y[0] = y_0 y[1] = y_1 for i in range(n): y[i + 2] = y[i + 1] + (self.step_size / 2) * ( 3 * self.func(x_1, y[i + 1]) - self.func(x_0, y[i]) ) x_0 = x_1 x_1 += self.step_size return y def step_3(self) -> np.ndarray: """ >>> def f(x, y): ... return x + y >>> y = AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_3() >>> float(y[3]) 0.15533333333333332 >>> AdamsBashforth(f, [0, 0.2], [0, 0], 0.2, 1).step_3() Traceback (most recent call last): ... ValueError: Insufficient initial points information. """ if len(self.x_initials) != 3 or len(self.y_initials) != 3: raise ValueError("Insufficient initial points information.") x_0, x_1, x_2 = self.x_initials[:3] y_0, y_1, y_2 = self.y_initials[:3] n = int((self.x_final - x_2) / self.step_size) y = np.zeros(n + 4) y[0] = y_0 y[1] = y_1 y[2] = y_2 for i in range(n + 1): y[i + 3] = y[i + 2] + (self.step_size / 12) * ( 23 * self.func(x_2, y[i + 2]) - 16 * self.func(x_1, y[i + 1]) + 5 * self.func(x_0, y[i]) ) x_0 = x_1 x_1 = x_2 x_2 += self.step_size return y def step_4(self) -> np.ndarray: """ >>> def f(x,y): ... return x + y >>> y = AdamsBashforth( ... f, [0, 0.2, 0.4, 0.6], [0, 0, 0.04, 0.128], 0.2, 1).step_4() >>> float(y[4]) 0.30699999999999994 >>> float(y[5]) 0.5771083333333333 >>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_4() Traceback (most recent call last): ... ValueError: Insufficient initial points information. """ if len(self.x_initials) != 4 or len(self.y_initials) != 4: raise ValueError("Insufficient initial points information.") x_0, x_1, x_2, x_3 = self.x_initials[:4] y_0, y_1, y_2, y_3 = self.y_initials[:4] n = int((self.x_final - x_3) / self.step_size) y = np.zeros(n + 4) y[0] = y_0 y[1] = y_1 y[2] = y_2 y[3] = y_3 for i in range(n): y[i + 4] = y[i + 3] + (self.step_size / 24) * ( 55 * self.func(x_3, y[i + 3]) - 59 * self.func(x_2, y[i + 2]) + 37 * self.func(x_1, y[i + 1]) - 9 * self.func(x_0, y[i]) ) x_0 = x_1 x_1 = x_2 x_2 = x_3 x_3 += self.step_size return y def step_5(self) -> np.ndarray: """ >>> def f(x,y): ... return x + y >>> y = AdamsBashforth( ... f, [0, 0.2, 0.4, 0.6, 0.8], [0, 0.02140, 0.02140, 0.22211, 0.42536], ... 0.2, 1).step_5() >>> float(y[-1]) 0.05436839444444452 >>> AdamsBashforth(f, [0, 0.2, 0.4], [0, 0, 0.04], 0.2, 1).step_5() Traceback (most recent call last): ... ValueError: Insufficient initial points information. """ if len(self.x_initials) != 5 or len(self.y_initials) != 5: raise ValueError("Insufficient initial points information.") x_0, x_1, x_2, x_3, x_4 = self.x_initials[:5] y_0, y_1, y_2, y_3, y_4 = self.y_initials[:5] n = int((self.x_final - x_4) / self.step_size) y = np.zeros(n + 6) y[0] = y_0 y[1] = y_1 y[2] = y_2 y[3] = y_3 y[4] = y_4 for i in range(n + 1): y[i + 5] = y[i + 4] + (self.step_size / 720) * ( 1901 * self.func(x_4, y[i + 4]) - 2774 * self.func(x_3, y[i + 3]) - 2616 * self.func(x_2, y[i + 2]) - 1274 * self.func(x_1, y[i + 1]) + 251 * self.func(x_0, y[i]) ) x_0 = x_1 x_1 = x_2 x_2 = x_3 x_3 = x_4 x_4 += self.step_size return y if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/simpson_rule.py
maths/numerical_analysis/simpson_rule.py
""" Numerical integration or quadrature for a smooth function f with known values at x_i This method is the classical approach of summing 'Equally Spaced Abscissas' method 2: "Simpson Rule" """ def method_2(boundary: list[int], steps: int) -> float: # "Simpson Rule" # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) """ Calculate the definite integral of a function using Simpson's Rule. :param boundary: A list containing the lower and upper bounds of integration. :param steps: The number of steps or resolution for the integration. :return: The approximate integral value. >>> round(method_2([0, 2, 4], 10), 10) 2.6666666667 >>> round(method_2([2, 0], 10), 10) -0.2666666667 >>> round(method_2([-2, -1], 10), 10) 2.172 >>> round(method_2([0, 1], 10), 10) 0.3333333333 >>> round(method_2([0, 2], 10), 10) 2.6666666667 >>> round(method_2([0, 2], 100), 10) 2.5621226667 >>> round(method_2([0, 1], 1000), 10) 0.3320026653 >>> round(method_2([0, 2], 0), 10) Traceback (most recent call last): ... ZeroDivisionError: Number of steps must be greater than zero >>> round(method_2([0, 2], -10), 10) Traceback (most recent call last): ... ZeroDivisionError: Number of steps must be greater than zero """ if steps <= 0: raise ZeroDivisionError("Number of steps must be greater than zero") h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] x_i = make_points(a, b, h) y = 0.0 y += (h / 3.0) * f(a) cnt = 2 for i in x_i: y += (h / 3) * (4 - 2 * (cnt % 2)) * f(i) cnt += 1 y += (h / 3.0) * f(b) return y def make_points(a, b, h): x = a + h while x < (b - h): yield x x = x + h def f(x): # enter your function here y = (x - 0) * (x - 0) return y def main(): a = 0.0 # Lower bound of integration b = 1.0 # Upper bound of integration steps = 10.0 # number of steps or resolution boundary = [a, b] # boundary of integration y = method_2(boundary, steps) print(f"y = {y}") if __name__ == "__main__": import doctest doctest.testmod() main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/bisection_2.py
maths/numerical_analysis/bisection_2.py
""" Given a function on floating number f(x) and two floating numbers `a` and `b` such that f(a) * f(b) < 0 and f(x) is continuous in [a, b]. Here f(x) represents algebraic or transcendental equation. Find root of function in interval [a, b] (Or find a value of x such that f(x) is 0) https://en.wikipedia.org/wiki/Bisection_method """ def equation(x: float) -> float: """ >>> equation(5) -15 >>> equation(0) 10 >>> equation(-5) -15 >>> equation(0.1) 9.99 >>> equation(-0.1) 9.99 """ return 10 - x * x def bisection(a: float, b: float) -> float: """ >>> bisection(-2, 5) 3.1611328125 >>> bisection(0, 6) 3.158203125 >>> bisection(2, 3) Traceback (most recent call last): ... ValueError: Wrong space! """ # 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 if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/weierstrass_method.py
maths/numerical_analysis/weierstrass_method.py
from collections.abc import Callable import numpy as np def weierstrass_method( polynomial: Callable[[np.ndarray], np.ndarray], degree: int, roots: np.ndarray | None = None, max_iter: int = 100, ) -> np.ndarray: """ Approximates all complex roots of a polynomial using the Weierstrass (Durand-Kerner) method. Args: polynomial: A function that takes a NumPy array of complex numbers and returns the polynomial values at those points. degree: Degree of the polynomial (number of roots to find). Must be ≥ 1. roots: Optional initial guess as a NumPy array of complex numbers. Must have length equal to 'degree'. If None, perturbed complex roots of unity are used. max_iter: Number of iterations to perform (default: 100). Returns: np.ndarray: Array of approximated complex roots. Raises: ValueError: If degree < 1, or if initial roots length doesn't match the degree. Note: - Root updates are clipped to prevent numerical overflow. Example: >>> import numpy as np >>> def check(poly, degree, expected): ... roots = weierstrass_method(poly, degree) ... return np.allclose(np.sort(roots), np.sort(expected)) >>> check( ... lambda x: x**2 - 1, ... 2, ... np.array([-1, 1])) True >>> check( ... lambda x: x**3 - 4.5*x**2 + 5.75*x - 1.875, ... 3, ... np.array([1.5, 0.5, 2.5]) ... ) True See Also: https://en.wikipedia.org/wiki/Durand%E2%80%93Kerner_method """ if degree < 1: raise ValueError("Degree of the polynomial must be at least 1.") if roots is None: # Use perturbed complex roots of unity as initial guesses rng = np.random.default_rng() roots = np.array( [ np.exp(2j * np.pi * i / degree) * (1 + 1e-3 * rng.random()) for i in range(degree) ], dtype=np.complex128, ) else: roots = np.asarray(roots, dtype=np.complex128) if roots.shape[0] != degree: raise ValueError( "Length of initial roots must match the degree of the polynomial." ) for _ in range(max_iter): # Construct the product denominator for each root denominator = np.array([root - roots for root in roots], dtype=np.complex128) np.fill_diagonal(denominator, 1.0) # Avoid zero in diagonal denominator = np.prod(denominator, axis=1) # Evaluate polynomial at each root numerator = polynomial(roots).astype(np.complex128) # Compute update and clip to prevent overflow delta = numerator / denominator delta = np.clip(delta, -1e10, 1e10) roots -= delta return roots if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/integration_by_simpson_approx.py
maths/numerical_analysis/integration_by_simpson_approx.py
""" Author : Syed Faizan ( 3rd Year IIIT Pune ) Github : faizan2700 Purpose : You have one function f(x) which takes float integer and returns float you have to integrate the function in limits a to b. The approximation proposed by Thomas Simpson in 1743 is one way to calculate integration. ( read article : https://cp-algorithms.com/num_methods/simpson-integration.html ) simpson_integration() takes function,lower_limit=a,upper_limit=b,precision and returns the integration of function in given limit. """ # constants # the more the number of steps the more accurate N_STEPS = 1000 def f(x: float) -> float: return x * x """ Summary of Simpson Approximation : By simpsons integration : 1. integration of fxdx with limit a to b is = f(x0) + 4 * f(x1) + 2 * f(x2) + 4 * f(x3) + 2 * f(x4)..... + f(xn) where x0 = a xi = a + i * h xn = b """ def simpson_integration(function, a: float, b: float, precision: int = 4) -> float: """ Args: function : the function which's integration is desired a : the lower limit of integration b : upper limit of integration precision : precision of the result,error required default is 4 Returns: result : the value of the approximated integration of function in range a to b Raises: AssertionError: function is not callable AssertionError: a is not float or integer AssertionError: function should return float or integer AssertionError: b is not float or integer AssertionError: precision is not positive integer >>> simpson_integration(lambda x : x*x,1,2,3) 2.333 >>> simpson_integration(lambda x : x*x,'wrong_input',2,3) Traceback (most recent call last): ... AssertionError: a should be float or integer your input : wrong_input >>> simpson_integration(lambda x : x*x,1,'wrong_input',3) Traceback (most recent call last): ... AssertionError: b should be float or integer your input : wrong_input >>> simpson_integration(lambda x : x*x,1,2,'wrong_input') Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : wrong_input >>> simpson_integration('wrong_input',2,3,4) Traceback (most recent call last): ... AssertionError: the function(object) passed should be callable your input : ... >>> simpson_integration(lambda x : x*x,3.45,3.2,1) -2.8 >>> simpson_integration(lambda x : x*x,3.45,3.2,0) Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : 0 >>> simpson_integration(lambda x : x*x,3.45,3.2,-1) Traceback (most recent call last): ... AssertionError: precision should be positive integer your input : -1 """ assert callable(function), ( f"the function(object) passed should be callable your input : {function}" ) assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}" assert isinstance(function(a), (float, int)), ( "the function should return integer or float return type of your function, " f"{type(a)}" ) assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}" assert isinstance(precision, int) and precision > 0, ( f"precision should be positive integer your input : {precision}" ) # just applying the formula of simpson for approximate integration written in # mentioned article in first comment of this file and above this function h = (b - a) / N_STEPS result = function(a) + function(b) for i in range(1, N_STEPS): a1 = a + h * i result += function(a1) * (4 if i % 2 else 2) result *= h / 3 return round(result, precision) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/runge_kutta.py
maths/numerical_analysis/runge_kutta.py
import numpy as np def runge_kutta(f, y0, x0, h, x_end): """ Calculate the numeric solution at each step to the ODE f(x, y) using RK4 https://en.wikipedia.org/wiki/Runge-Kutta_methods Arguments: f -- The ode as a function of x and y y0 -- the initial value for y x0 -- the initial value for x h -- the stepsize x_end -- the end value for x >>> # the exact solution is math.exp(x) >>> def f(x, y): ... return y >>> y0 = 1 >>> y = runge_kutta(f, y0, 0.0, 0.01, 5) >>> float(y[-1]) 148.41315904125113 """ n = int(np.ceil((x_end - x0) / h)) y = np.zeros((n + 1,)) y[0] = y0 x = x0 for k in range(n): k1 = f(x, y[k]) k2 = f(x + 0.5 * h, y[k] + 0.5 * h * k1) k3 = f(x + 0.5 * h, y[k] + 0.5 * h * k2) k4 = f(x + h, y[k] + h * k3) y[k + 1] = y[k] + (1 / 6) * h * (k1 + 2 * k2 + 2 * k3 + k4) x += h return y if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/__init__.py
maths/numerical_analysis/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/square_root.py
maths/numerical_analysis/square_root.py
import math def fx(x: float, a: float) -> float: return math.pow(x, 2) - a def fx_derivative(x: float) -> float: return 2 * x def get_initial_point(a: float) -> float: start = 2.0 while start <= a: start = math.pow(start, 2) return start def square_root_iterative( a: float, max_iter: int = 9999, tolerance: float = 1e-14 ) -> float: """ Square root approximated using Newton's method. https://en.wikipedia.org/wiki/Newton%27s_method >>> all(abs(square_root_iterative(i) - math.sqrt(i)) <= 1e-14 for i in range(500)) True >>> square_root_iterative(-1) Traceback (most recent call last): ... ValueError: math domain error >>> square_root_iterative(4) 2.0 >>> square_root_iterative(3.2) 1.788854381999832 >>> square_root_iterative(140) 11.832159566199232 """ if a < 0: raise ValueError("math domain error") value = get_initial_point(a) for _ in range(max_iter): prev_value = value value = value - fx(value, a) / fx_derivative(value) if abs(prev_value - value) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/proper_fractions.py
maths/numerical_analysis/proper_fractions.py
from math import gcd def proper_fractions(denominator: int) -> list[str]: """ this algorithm returns a list of proper fractions, in the range between 0 and 1, which can be formed with the given denominator https://en.wikipedia.org/wiki/Fraction#Proper_and_improper_fractions >>> proper_fractions(10) ['1/10', '3/10', '7/10', '9/10'] >>> proper_fractions(5) ['1/5', '2/5', '3/5', '4/5'] >>> proper_fractions(-15) Traceback (most recent call last): ... ValueError: The Denominator Cannot be less than 0 >>> proper_fractions(0) [] >>> proper_fractions(1.2) Traceback (most recent call last): ... ValueError: The Denominator must be an integer """ if denominator < 0: raise ValueError("The Denominator Cannot be less than 0") elif isinstance(denominator, float): raise ValueError("The Denominator must be an integer") return [ f"{numerator}/{denominator}" for numerator in range(1, denominator) if gcd(numerator, denominator) == 1 ] if __name__ == "__main__": from doctest import testmod testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/numerical_analysis/nevilles_method.py
maths/numerical_analysis/nevilles_method.py
""" Python program to show how to interpolate and evaluate a polynomial using Neville's method. Neville's method evaluates a polynomial that passes through a given set of x and y points for a particular x value (x0) using the Newton polynomial form. Reference: https://rpubs.com/aaronsc32/nevilles-method-polynomial-interpolation """ def neville_interpolate(x_points: list, y_points: list, x0: int) -> list: """ Interpolate and evaluate a polynomial using Neville's method. Arguments: x_points, y_points: Iterables of x and corresponding y points through which the polynomial passes. x0: The value of x to evaluate the polynomial for. Return Value: A list of the approximated value and the Neville iterations table respectively. >>> import pprint >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 5)[0] 10.0 >>> pprint.pprint(neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 99)[1]) [[0, 6, 0, 0, 0], [0, 7, 0, 0, 0], [0, 8, 104.0, 0, 0], [0, 9, 104.0, 104.0, 0], [0, 11, 104.0, 104.0, 104.0]] >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 99)[0] 104.0 >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), '') Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'str' and 'int' """ n = len(x_points) q = [[0] * n for i in range(n)] for i in range(n): q[i][1] = y_points[i] for i in range(2, n): for j in range(i, n): q[j][i] = ( (x0 - x_points[j - i + 1]) * q[j][i - 1] - (x0 - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/polynomials/single_indeterminate_operations.py
maths/polynomials/single_indeterminate_operations.py
""" This module implements a single indeterminate polynomials class with some basic operations Reference: https://en.wikipedia.org/wiki/Polynomial """ from __future__ import annotations from collections.abc import MutableSequence class Polynomial: def __init__(self, degree: int, coefficients: MutableSequence[float]) -> None: """ The coefficients should be in order of degree, from smallest to largest. >>> p = Polynomial(2, [1, 2, 3]) >>> p = Polynomial(2, [1, 2, 3, 4]) Traceback (most recent call last): ... ValueError: The number of coefficients should be equal to the degree + 1. """ 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 def __add__(self, polynomial_2: Polynomial) -> Polynomial: """ Polynomial addition >>> p = Polynomial(2, [1, 2, 3]) >>> q = Polynomial(2, [1, 2, 3]) >>> p + q 6x^2 + 4x + 2 """ 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) def __sub__(self, polynomial_2: Polynomial) -> Polynomial: """ Polynomial subtraction >>> p = Polynomial(2, [1, 2, 4]) >>> q = Polynomial(2, [1, 2, 3]) >>> p - q 1x^2 """ return self + polynomial_2 * Polynomial(0, [-1]) def __neg__(self) -> Polynomial: """ Polynomial negation >>> p = Polynomial(2, [1, 2, 3]) >>> -p - 3x^2 - 2x - 1 """ return Polynomial(self.degree, [-c for c in self.coefficients]) def __mul__(self, polynomial_2: Polynomial) -> Polynomial: """ Polynomial multiplication >>> p = Polynomial(2, [1, 2, 3]) >>> q = Polynomial(2, [1, 2, 3]) >>> p * q 9x^4 + 12x^3 + 10x^2 + 4x + 1 """ 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) def evaluate(self, substitution: float) -> float: """ Evaluates the polynomial at x. >>> p = Polynomial(2, [1, 2, 3]) >>> p.evaluate(2) 17 """ result: int | float = 0 for i in range(self.degree + 1): result += self.coefficients[i] * (substitution**i) return result def __str__(self) -> str: """ >>> p = Polynomial(2, [1, 2, 3]) >>> print(p) 3x^2 + 2x + 1 """ 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 def __repr__(self) -> str: """ >>> p = Polynomial(2, [1, 2, 3]) >>> p 3x^2 + 2x + 1 """ return self.__str__() def derivative(self) -> Polynomial: """ Returns the derivative of the polynomial. >>> p = Polynomial(2, [1, 2, 3]) >>> p.derivative() 6x + 2 """ 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) def integral(self, constant: float = 0) -> Polynomial: """ Returns the integral of the polynomial. >>> p = Polynomial(2, [1, 2, 3]) >>> p.integral() 1.0x^3 + 1.0x^2 + 1.0x """ 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) def __eq__(self, polynomial_2: object) -> bool: """ Checks if two polynomials are equal. >>> p = Polynomial(2, [1, 2, 3]) >>> q = Polynomial(2, [1, 2, 3]) >>> p == q True """ 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 def __ne__(self, polynomial_2: object) -> bool: """ Checks if two polynomials are not equal. >>> p = Polynomial(2, [1, 2, 3]) >>> q = Polynomial(2, [1, 2, 3]) >>> p != q False """ return not self.__eq__(polynomial_2)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/polynomials/__init__.py
maths/polynomials/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/perfect_number.py
maths/special_numbers/perfect_number.py
""" == Perfect Number == In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For example: 6 ==> divisors[1, 2, 3, 6] Excluding 6, the sum(divisors) is 1 + 2 + 3 = 6 So, 6 is a Perfect Number Other examples of Perfect Numbers: 28, 486, ... https://en.wikipedia.org/wiki/Perfect_number """ def perfect(number: int) -> bool: """ Check if a number is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). Args: number: The number to be checked. Returns: True if the number is a perfect number, False otherwise. Start from 1 because dividing by 0 will raise ZeroDivisionError. A number at most can be divisible by the half of the number except the number itself. For example, 6 is at most can be divisible by 3 except by 6 itself. Examples: >>> perfect(27) False >>> perfect(28) True >>> perfect(29) False >>> perfect(6) True >>> perfect(12) False >>> perfect(496) True >>> perfect(8128) True >>> perfect(0) False >>> perfect(-1) False >>> perfect(12.34) Traceback (most recent call last): ... ValueError: number must be an integer >>> perfect("Hello") Traceback (most recent call last): ... ValueError: number must be an integer """ if not isinstance(number, int): raise ValueError("number must be an integer") if number <= 0: return False return sum(i for i in range(1, number // 2 + 1) if number % i == 0) == number if __name__ == "__main__": from doctest import testmod testmod() print("Program to check whether a number is a Perfect number or not...") try: number = int(input("Enter a positive integer: ").strip()) except ValueError: msg = "number must be an integer" print(msg) raise ValueError(msg) print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/ugly_numbers.py
maths/special_numbers/ugly_numbers.py
""" Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the first 11 ugly numbers. By convention, 1 is included. Given an integer n, we have to find the nth ugly number. For more details, refer this article https://www.geeksforgeeks.org/ugly-numbers/ """ def ugly_numbers(n: int) -> int: """ Returns the nth ugly number. >>> ugly_numbers(100) 1536 >>> ugly_numbers(0) 1 >>> ugly_numbers(20) 36 >>> ugly_numbers(-5) 1 >>> ugly_numbers(-5.5) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer """ ugly_nums = [1] i2, i3, i5 = 0, 0, 0 next_2 = ugly_nums[i2] * 2 next_3 = ugly_nums[i3] * 3 next_5 = ugly_nums[i5] * 5 for _ in range(1, n): next_num = min(next_2, next_3, next_5) ugly_nums.append(next_num) if next_num == next_2: i2 += 1 next_2 = ugly_nums[i2] * 2 if next_num == next_3: i3 += 1 next_3 = ugly_nums[i3] * 3 if next_num == next_5: i5 += 1 next_5 = ugly_nums[i5] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(f"{ugly_numbers(200) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/catalan_number.py
maths/special_numbers/catalan_number.py
""" Calculate the nth Catalan number Source: https://en.wikipedia.org/wiki/Catalan_number """ def catalan(number: int) -> int: """ :param number: nth catalan number to calculate :return: the nth catalan number Note: A catalan number is only defined for positive integers >>> catalan(5) 14 >>> catalan(0) Traceback (most recent call last): ... ValueError: Input value of [number=0] must be > 0 >>> catalan(-1) Traceback (most recent call last): ... ValueError: Input value of [number=-1] must be > 0 >>> catalan(5.0) Traceback (most recent call last): ... TypeError: Input value of [number=5.0] must be an integer """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: msg = f"Input value of [number={number}] must be > 0" raise ValueError(msg) current_number = 1 for i in range(1, number): current_number *= 4 * i - 2 current_number //= i + 1 return current_number if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/harshad_numbers.py
maths/special_numbers/harshad_numbers.py
""" A harshad number (or more specifically an n-harshad number) is a number that's divisible by the sum of its digits in some given base n. Reference: https://en.wikipedia.org/wiki/Harshad_number """ def int_to_base(number: int, base: int) -> str: """ Convert a given positive decimal integer to base 'base'. Where 'base' ranges from 2 to 36. Examples: >>> int_to_base(0, 21) '0' >>> int_to_base(23, 2) '10111' >>> int_to_base(58, 5) '213' >>> int_to_base(167, 16) 'A7' >>> # bases below 2 and beyond 36 will error >>> int_to_base(98, 1) Traceback (most recent call last): ... ValueError: 'base' must be between 2 and 36 inclusive >>> int_to_base(98, 37) Traceback (most recent call last): ... ValueError: 'base' must be between 2 and 36 inclusive >>> int_to_base(-99, 16) Traceback (most recent call last): ... ValueError: number must be a positive integer """ if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" result = "" if number < 0: raise ValueError("number must be a positive integer") while number > 0: number, remainder = divmod(number, base) result = digits[remainder] + result if result == "": result = "0" return result def sum_of_digits(num: int, base: int) -> str: """ Calculate the sum of digit values in a positive integer converted to the given 'base'. Where 'base' ranges from 2 to 36. Examples: >>> sum_of_digits(103, 12) '13' >>> sum_of_digits(1275, 4) '30' >>> sum_of_digits(6645, 2) '1001' >>> # bases below 2 and beyond 36 will error >>> sum_of_digits(543, 1) Traceback (most recent call last): ... ValueError: 'base' must be between 2 and 36 inclusive >>> sum_of_digits(543, 37) Traceback (most recent call last): ... ValueError: 'base' must be between 2 and 36 inclusive """ if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") num_str = int_to_base(num, base) res = sum(int(char, base) for char in num_str) res_str = int_to_base(res, base) return res_str def harshad_numbers_in_base(limit: int, base: int) -> list[str]: """ Finds all Harshad numbers smaller than num in base 'base'. Where 'base' ranges from 2 to 36. Examples: >>> harshad_numbers_in_base(15, 2) ['1', '10', '100', '110', '1000', '1010', '1100'] >>> harshad_numbers_in_base(12, 34) ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B'] >>> harshad_numbers_in_base(12, 4) ['1', '2', '3', '10', '12', '20', '21'] >>> # bases below 2 and beyond 36 will error >>> harshad_numbers_in_base(234, 37) Traceback (most recent call last): ... ValueError: 'base' must be between 2 and 36 inclusive >>> harshad_numbers_in_base(234, 1) Traceback (most recent call last): ... ValueError: 'base' must be between 2 and 36 inclusive >>> harshad_numbers_in_base(-12, 6) [] """ if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") if limit < 0: return [] numbers = [ int_to_base(i, base) for i in range(1, limit) if i % int(sum_of_digits(i, base), base) == 0 ] return numbers def is_harshad_number_in_base(num: int, base: int) -> bool: """ Determines whether n in base 'base' is a harshad number. Where 'base' ranges from 2 to 36. Examples: >>> is_harshad_number_in_base(18, 10) True >>> is_harshad_number_in_base(21, 10) True >>> is_harshad_number_in_base(-21, 5) False >>> # bases below 2 and beyond 36 will error >>> is_harshad_number_in_base(45, 37) Traceback (most recent call last): ... ValueError: 'base' must be between 2 and 36 inclusive >>> is_harshad_number_in_base(45, 1) Traceback (most recent call last): ... ValueError: 'base' must be between 2 and 36 inclusive """ if base < 2 or base > 36: raise ValueError("'base' must be between 2 and 36 inclusive") if num < 0: return False n = int_to_base(num, base) d = sum_of_digits(num, base) return int(n, base) % int(d, base) == 0 if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/happy_number.py
maths/special_numbers/happy_number.py
def is_happy_number(number: int) -> bool: """ A happy number is a number which eventually reaches 1 when replaced by the sum of the square of each digit. :param number: The number to check for happiness. :return: True if the number is a happy number, False otherwise. >>> is_happy_number(19) True >>> is_happy_number(2) False >>> is_happy_number(23) True >>> is_happy_number(1) True >>> is_happy_number(0) Traceback (most recent call last): ... ValueError: number=0 must be a positive integer >>> is_happy_number(-19) Traceback (most recent call last): ... ValueError: number=-19 must be a positive integer >>> is_happy_number(19.1) Traceback (most recent call last): ... ValueError: number=19.1 must be a positive integer >>> is_happy_number("happy") Traceback (most recent call last): ... ValueError: number='happy' must be a positive integer """ if not isinstance(number, int) or number <= 0: msg = f"{number=} must be a positive integer" raise ValueError(msg) seen = set() while number != 1 and number not in seen: seen.add(number) number = sum(int(digit) ** 2 for digit in str(number)) return number == 1 if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/krishnamurthy_number.py
maths/special_numbers/krishnamurthy_number.py
""" == Krishnamurthy Number == It is also known as Peterson Number A Krishnamurthy Number is a number whose sum of the factorial of the digits equals to the original number itself. For example: 145 = 1! + 4! + 5! So, 145 is a Krishnamurthy Number """ def factorial(digit: int) -> int: """ >>> factorial(3) 6 >>> factorial(0) 1 >>> factorial(5) 120 """ return 1 if digit in (0, 1) else (digit * factorial(digit - 1)) def krishnamurthy(number: int) -> bool: """ >>> krishnamurthy(145) True >>> krishnamurthy(240) False >>> krishnamurthy(1) True """ fact_sum = 0 duplicate = number while duplicate > 0: duplicate, digit = divmod(duplicate, 10) fact_sum += factorial(digit) return fact_sum == number if __name__ == "__main__": print("Program to check whether a number is a Krisnamurthy Number or not.") number = int(input("Enter number: ").strip()) print( f"{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number." )
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/pronic_number.py
maths/special_numbers/pronic_number.py
""" == Pronic Number == A number n is said to be a Proic number if there exists an integer m such that n = m * (m + 1) Examples of Proic Numbers: 0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110 ... https://en.wikipedia.org/wiki/Pronic_number """ # Author : Akshay Dubey (https://github.com/itsAkshayDubey) def is_pronic(number: int) -> bool: """ # doctest: +NORMALIZE_WHITESPACE This functions takes an integer number as input. returns True if the number is pronic. >>> is_pronic(-1) False >>> is_pronic(0) True >>> is_pronic(2) True >>> is_pronic(5) False >>> is_pronic(6) True >>> is_pronic(8) False >>> is_pronic(30) True >>> is_pronic(32) False >>> is_pronic(2147441940) True >>> is_pronic(9223372033963249500) True >>> is_pronic(6.0) Traceback (most recent call last): ... TypeError: Input value of [number=6.0] must be an integer """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 0 or number % 2 == 1: return False number_sqrt = int(number**0.5) return number == number_sqrt * (number_sqrt + 1) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/automorphic_number.py
maths/special_numbers/automorphic_number.py
""" == Automorphic Numbers == A number n is said to be a Automorphic number if the square of n "ends" in the same digits as n itself. Examples of Automorphic Numbers: 0, 1, 5, 6, 25, 76, 376, 625, 9376, 90625, ... https://en.wikipedia.org/wiki/Automorphic_number """ # Author : Akshay Dubey (https://github.com/itsAkshayDubey) # Time Complexity : O(log10n) def is_automorphic_number(number: int) -> bool: """ # doctest: +NORMALIZE_WHITESPACE This functions takes an integer number as input. returns True if the number is automorphic. >>> is_automorphic_number(-1) False >>> is_automorphic_number(0) True >>> is_automorphic_number(5) True >>> is_automorphic_number(6) True >>> is_automorphic_number(7) False >>> is_automorphic_number(25) True >>> is_automorphic_number(259918212890625) True >>> is_automorphic_number(259918212890636) False >>> is_automorphic_number(740081787109376) True >>> is_automorphic_number(5.0) Traceback (most recent call last): ... TypeError: Input value of [number=5.0] must be an integer """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) 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 if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/hexagonal_number.py
maths/special_numbers/hexagonal_number.py
""" == Hexagonal Number == The nth hexagonal number hn is the number of distinct dots in a pattern of dots consisting of the outlines of regular hexagons with sides up to n dots, when the hexagons are overlaid so that they share one vertex. https://en.wikipedia.org/wiki/Hexagonal_number """ # Author : Akshay Dubey (https://github.com/itsAkshayDubey) def hexagonal(number: int) -> int: """ :param number: nth hexagonal number to calculate :return: the nth hexagonal number Note: A hexagonal number is only defined for positive integers >>> hexagonal(4) 28 >>> hexagonal(11) 231 >>> hexagonal(22) 946 >>> hexagonal(0) Traceback (most recent call last): ... ValueError: Input must be a positive integer >>> hexagonal(-1) Traceback (most recent call last): ... ValueError: Input must be a positive integer >>> hexagonal(11.0) Traceback (most recent call last): ... TypeError: Input value of [number=11.0] must be an integer """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: raise ValueError("Input must be a positive integer") return number * (2 * number - 1) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/carmichael_number.py
maths/special_numbers/carmichael_number.py
""" == Carmichael Numbers == A number n is said to be a Carmichael number if it satisfies the following modular arithmetic condition: power(b, n-1) MOD n = 1, for all b ranging from 1 to n such that b and n are relatively prime, i.e, gcd(b, n) = 1 Examples of Carmichael Numbers: 561, 1105, ... https://en.wikipedia.org/wiki/Carmichael_number """ from maths.greatest_common_divisor import greatest_common_divisor def power(x: int, y: int, mod: int) -> int: """ Examples: >>> power(2, 15, 3) 2 >>> power(5, 1, 30) 5 """ if y == 0: return 1 temp = power(x, y // 2, mod) % mod temp = (temp * temp) % mod if y % 2 == 1: temp = (temp * x) % mod return temp def is_carmichael_number(n: int) -> bool: """ Examples: >>> is_carmichael_number(4) False >>> is_carmichael_number(561) True >>> is_carmichael_number(562) False >>> is_carmichael_number(900) False >>> is_carmichael_number(1105) True >>> is_carmichael_number(8911) True >>> is_carmichael_number(5.1) Traceback (most recent call last): ... ValueError: Number 5.1 must instead be a positive integer >>> is_carmichael_number(-7) Traceback (most recent call last): ... ValueError: Number -7 must instead be a positive integer >>> is_carmichael_number(0) Traceback (most recent call last): ... ValueError: Number 0 must instead be a positive integer """ if n <= 0 or not isinstance(n, int): msg = f"Number {n} must instead be a positive integer" raise ValueError(msg) return all( power(b, n - 1, n) == 1 for b in range(2, n) if greatest_common_divisor(b, n) == 1 ) if __name__ == "__main__": import doctest doctest.testmod() number = int(input("Enter number: ").strip()) if is_carmichael_number(number): print(f"{number} is a Carmichael Number.") else: print(f"{number} is not a Carmichael Number.")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/triangular_numbers.py
maths/special_numbers/triangular_numbers.py
""" A triangular number or triangle number counts objects arranged in an equilateral triangle. This module provides a function to generate n'th triangular number. For more information about triangular numbers, refer to: https://en.wikipedia.org/wiki/Triangular_number """ def triangular_number(position: int) -> int: """ Generate the triangular number at the specified position. Args: position (int): The position of the triangular number to generate. Returns: int: The triangular number at the specified position. Raises: ValueError: If `position` is negative. Examples: >>> triangular_number(1) 1 >>> triangular_number(3) 6 >>> triangular_number(-1) Traceback (most recent call last): ... ValueError: param `position` must be non-negative """ if position < 0: raise ValueError("param `position` must be non-negative") return position * (position + 1) // 2 if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/hamming_numbers.py
maths/special_numbers/hamming_numbers.py
""" A Hamming number is a positive integer of the form 2^i*3^j*5^k, for some non-negative integers i, j, and k. They are often referred to as regular numbers. More info at: https://en.wikipedia.org/wiki/Regular_number. """ def hamming(n_element: int) -> list: """ This function creates an ordered list of n length as requested, and afterwards returns the last value of the list. It must be given a positive integer. :param n_element: The number of elements on the list :return: The nth element of the list >>> hamming(-5) Traceback (most recent call last): ... ValueError: n_element should be a positive number >>> hamming(5) [1, 2, 3, 4, 5] >>> hamming(10) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] >>> hamming(15) [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24] """ n_element = int(n_element) if n_element < 1: my_error = ValueError("n_element should be a positive number") raise my_error hamming_list = [1] i, j, k = (0, 0, 0) index = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2, hamming_list[j] * 3, hamming_list[k] * 5) ) index += 1 return hamming_list if __name__ == "__main__": n = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") hamming_numbers = hamming(int(n)) print("-----------------------------------------------------") print(f"The list with nth numbers is: {hamming_numbers}") print("-----------------------------------------------------")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/weird_number.py
maths/special_numbers/weird_number.py
""" https://en.wikipedia.org/wiki/Weird_number Fun fact: The set of weird numbers has positive asymptotic density. """ from math import sqrt def factors(number: int) -> list[int]: """ >>> factors(12) [1, 2, 3, 4, 6] >>> factors(1) [1] >>> factors(100) [1, 2, 4, 5, 10, 20, 25, 50] # >>> factors(-12) # [1, 2, 3, 4, 6] """ values = [1] for i in range(2, int(sqrt(number)) + 1, 1): if number % i == 0: values.append(i) if int(number // i) != i: values.append(int(number // i)) return sorted(values) def abundant(n: int) -> bool: """ >>> abundant(0) True >>> abundant(1) False >>> abundant(12) True >>> abundant(13) False >>> abundant(20) True # >>> abundant(-12) # True """ return sum(factors(n)) > n def semi_perfect(number: int) -> bool: """ >>> semi_perfect(0) True >>> semi_perfect(1) True >>> semi_perfect(12) True >>> semi_perfect(13) False # >>> semi_perfect(-12) # True """ values = factors(number) r = len(values) subset = [[0 for i in range(number + 1)] for j in range(r + 1)] for i in range(r + 1): subset[i][0] = True for i in range(1, number + 1): subset[0][i] = False for i in range(1, r + 1): for j in range(1, number + 1): if j < values[i - 1]: subset[i][j] = subset[i - 1][j] else: subset[i][j] = subset[i - 1][j] or subset[i - 1][j - values[i - 1]] return subset[r][number] != 0 def weird(number: int) -> bool: """ >>> weird(0) False >>> weird(70) True >>> weird(77) False """ return abundant(number) and not semi_perfect(number) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) for number in (69, 70, 71): print(f"{number} is {'' if weird(number) else 'not '}weird.")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/bell_numbers.py
maths/special_numbers/bell_numbers.py
""" Bell numbers represent the number of ways to partition a set into non-empty subsets. This module provides functions to calculate Bell numbers for sets of integers. In other words, the first (n + 1) Bell numbers. For more information about Bell numbers, refer to: https://en.wikipedia.org/wiki/Bell_number """ def bell_numbers(max_set_length: int) -> list[int]: """ Calculate Bell numbers for the sets of lengths from 0 to max_set_length. In other words, calculate first (max_set_length + 1) Bell numbers. Args: max_set_length (int): The maximum length of the sets for which Bell numbers are calculated. Returns: list: A list of Bell numbers for sets of lengths from 0 to max_set_length. Examples: >>> bell_numbers(-2) Traceback (most recent call last): ... ValueError: max_set_length must be non-negative >>> bell_numbers(0) [1] >>> bell_numbers(1) [1, 1] >>> bell_numbers(5) [1, 1, 2, 5, 15, 52] """ if max_set_length < 0: raise ValueError("max_set_length must be non-negative") bell = [0] * (max_set_length + 1) bell[0] = 1 for i in range(1, max_set_length + 1): for j in range(i): bell[i] += _binomial_coefficient(i - 1, j) * bell[j] return bell def _binomial_coefficient(total_elements: int, elements_to_choose: int) -> int: """ Calculate the binomial coefficient C(total_elements, elements_to_choose) Args: total_elements (int): The total number of elements. elements_to_choose (int): The number of elements to choose. Returns: int: The binomial coefficient C(total_elements, elements_to_choose). Examples: >>> _binomial_coefficient(5, 2) 10 >>> _binomial_coefficient(6, 3) 20 """ if elements_to_choose in {0, total_elements}: return 1 elements_to_choose = min(elements_to_choose, total_elements - elements_to_choose) coefficient = 1 for i in range(elements_to_choose): coefficient *= total_elements - i coefficient //= i + 1 return coefficient if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/__init__.py
maths/special_numbers/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/armstrong_numbers.py
maths/special_numbers/armstrong_numbers.py
""" An Armstrong number is equal to the sum of its own digits each raised to the power of the number of digits. For example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370. Armstrong numbers are also called Narcissistic numbers and Pluperfect numbers. On-Line Encyclopedia of Integer Sequences entry: https://oeis.org/A005188 """ PASSING = (1, 153, 370, 371, 1634, 24678051, 115132219018763992565095597973971522401) FAILING: tuple = (-153, -1, 0, 1.2, 200, "A", [], {}, None) def armstrong_number(n: int) -> bool: """ Return True if n is an Armstrong number or False if it is not. >>> all(armstrong_number(n) for n in PASSING) True >>> any(armstrong_number(n) for n in FAILING) False """ if not isinstance(n, int) or n < 1: return False # Initialization of sum and number of digits. total = 0 number_of_digits = 0 temp = n # Calculation of digits of the number number_of_digits = len(str(n)) # Dividing number into separate digits and find Armstrong number temp = n while temp > 0: rem = temp % 10 total += rem**number_of_digits temp //= 10 return n == total def pluperfect_number(n: int) -> bool: """Return True if n is a pluperfect number or False if it is not >>> all(pluperfect_number(n) for n in PASSING) True >>> any(pluperfect_number(n) for n in FAILING) False """ if not isinstance(n, int) or n < 1: return False # Init a "histogram" of the digits digit_histogram = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] digit_total = 0 total = 0 temp = n while temp > 0: temp, rem = divmod(temp, 10) digit_histogram[rem] += 1 digit_total += 1 for cnt, i in zip(digit_histogram, range(len(digit_histogram))): total += cnt * i**digit_total return n == total def narcissistic_number(n: int) -> bool: """Return True if n is a narcissistic number or False if it is not. >>> all(narcissistic_number(n) for n in PASSING) True >>> any(narcissistic_number(n) for n in FAILING) False """ if not isinstance(n, int) or n < 1: return False expo = len(str(n)) # the power that all digits will be raised to # check if sum of each digit multiplied expo times is equal to number return n == sum(int(i) ** expo for i in str(n)) def main(): """ Request that user input an integer and tell them if it is Armstrong number. """ num = int(input("Enter an integer to see if it is an Armstrong number: ").strip()) print(f"{num} is {'' if armstrong_number(num) else 'not '}an Armstrong number.") print(f"{num} is {'' if narcissistic_number(num) else 'not '}an Armstrong number.") print(f"{num} is {'' if pluperfect_number(num) else 'not '}an Armstrong number.") if __name__ == "__main__": import doctest doctest.testmod() main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/polygonal_numbers.py
maths/special_numbers/polygonal_numbers.py
def polygonal_num(num: int, sides: int) -> int: """ Returns the `num`th `sides`-gonal number. It is assumed that `num` >= 0 and `sides` >= 3 (see for reference https://en.wikipedia.org/wiki/Polygonal_number). >>> polygonal_num(0, 3) 0 >>> polygonal_num(3, 3) 6 >>> polygonal_num(5, 4) 25 >>> polygonal_num(2, 5) 5 >>> polygonal_num(-1, 0) Traceback (most recent call last): ... ValueError: Invalid input: num must be >= 0 and sides must be >= 3. >>> polygonal_num(0, 2) Traceback (most recent call last): ... ValueError: Invalid input: num must be >= 0 and sides must be >= 3. """ if num < 0 or sides < 3: raise ValueError("Invalid input: num must be >= 0 and sides must be >= 3.") return ((sides - 2) * num**2 - (sides - 4) * num) // 2 if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/special_numbers/proth_number.py
maths/special_numbers/proth_number.py
""" Calculate the nth Proth number Source: https://handwiki.org/wiki/Proth_number """ import math def proth(number: int) -> int: """ :param number: nth number to calculate in the sequence :return: the nth number in Proth number Note: indexing starts at 1 i.e. proth(1) gives the first Proth number of 3 >>> proth(6) 25 >>> proth(0) Traceback (most recent call last): ... ValueError: Input value of [number=0] must be > 0 >>> proth(-1) Traceback (most recent call last): ... ValueError: Input value of [number=-1] must be > 0 >>> proth(6.0) Traceback (most recent call last): ... TypeError: Input value of [number=6.0] must be an integer """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: msg = f"Input value of [number={number}] must be > 0" raise ValueError(msg) elif number == 1: return 3 elif number == 2: return 5 else: """ +1 for binary starting at 0 i.e. 2^0, 2^1, etc. +1 to start the sequence at the 3rd Proth number Hence, we have a +2 in the below statement """ block_index = int(math.log(number // 3, 2)) + 2 proth_list = [3, 5] proth_index = 2 increment = 3 for block in range(1, block_index): for _ in range(increment): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1]) proth_index += 1 increment *= 2 return proth_list[number - 1] def is_proth_number(number: int) -> bool: """ :param number: positive integer number :return: true if number is a Proth number, false otherwise >>> is_proth_number(1) False >>> is_proth_number(2) False >>> is_proth_number(3) True >>> is_proth_number(4) False >>> is_proth_number(5) True >>> is_proth_number(34) False >>> is_proth_number(-1) Traceback (most recent call last): ... ValueError: Input value of [number=-1] must be > 0 >>> is_proth_number(6.0) Traceback (most recent call last): ... TypeError: Input value of [number=6.0] must be an integer """ if not isinstance(number, int): message = f"Input value of [{number=}] must be an integer" raise TypeError(message) if number <= 0: message = f"Input value of [{number=}] must be > 0" raise ValueError(message) if number == 1: return False number -= 1 n = 0 while number % 2 == 0: n += 1 number //= 2 return number < 2**n if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): value = 0 try: value = proth(number) except ValueError: print(f"ValueError: there is no {number}th Proth number") continue print(f"The {number}th Proth number: {value}") for number in [1, 2, 3, 4, 5, 9, 13, 49, 57, 193, 241, 163, 201]: if is_proth_number(number): print(f"{number} is a Proth number") else: print(f"{number} is not a Proth number")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/series/arithmetic.py
maths/series/arithmetic.py
""" Arithmetic mean Reference: https://en.wikipedia.org/wiki/Arithmetic_mean Arithmetic series Reference: https://en.wikipedia.org/wiki/Arithmetic_series (The URL above will redirect you to arithmetic progression) """ def is_arithmetic_series(series: list) -> bool: """ checking whether the input series is arithmetic series or not >>> is_arithmetic_series([2, 4, 6]) True >>> is_arithmetic_series([3, 6, 12, 24]) False >>> is_arithmetic_series([1, 2, 3]) True >>> is_arithmetic_series(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> is_arithmetic_series([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ 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 def arithmetic_mean(series: list) -> float: """ return the arithmetic mean of series >>> arithmetic_mean([2, 4, 6]) 4.0 >>> arithmetic_mean([3, 6, 9, 12]) 7.5 >>> arithmetic_mean(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> arithmetic_mean([4, 8, 1]) 4.333333333333333 >>> arithmetic_mean([1, 2, 3]) 2.0 >>> arithmetic_mean([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ 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) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/series/geometric_series.py
maths/series/geometric_series.py
""" This is a pure Python implementation of the Geometric Series algorithm https://en.wikipedia.org/wiki/Geometric_series Run the doctests with the following command: python3 -m doctest -v geometric_series.py or python -m doctest -v geometric_series.py For manual testing run: python3 geometric_series.py """ from __future__ import annotations def geometric_series( nth_term: float, start_term_a: float, common_ratio_r: float, ) -> list[float]: """ Pure Python implementation of Geometric Series algorithm :param nth_term: The last term (nth term of Geometric Series) :param start_term_a : The first term of Geometric Series :param common_ratio_r : The common ratio between all the terms :return: The Geometric Series starting from first term a and multiple of common ration with first term with increase in power till last term (nth term) Examples: >>> geometric_series(4, 2, 2) [2, 4.0, 8.0, 16.0] >>> geometric_series(4.0, 2.0, 2.0) [2.0, 4.0, 8.0, 16.0] >>> geometric_series(4.1, 2.1, 2.1) [2.1, 4.41, 9.261000000000001, 19.448100000000004] >>> geometric_series(4, 2, -2) [2, -4.0, 8.0, -16.0] >>> geometric_series(4, -2, 2) [-2, -4.0, -8.0, -16.0] >>> geometric_series(-4, 2, 2) [] >>> geometric_series(0, 100, 500) [] >>> geometric_series(1, 1, 1) [1] >>> geometric_series(0, 0, 0) [] """ if not all((nth_term, start_term_a, common_ratio_r)): return [] series: list[float] = [] 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 if __name__ == "__main__": import doctest doctest.testmod() nth_term = float(input("Enter the last number (n term) of the Geometric Series")) start_term_a = float(input("Enter the starting term (a) of the Geometric Series")) common_ratio_r = float( input("Enter the common ratio between two terms (r) of the Geometric Series") ) print("Formula of Geometric Series => a + ar + ar^2 ... +ar^n") print(geometric_series(nth_term, start_term_a, common_ratio_r))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/series/p_series.py
maths/series/p_series.py
""" This is a pure Python implementation of the P-Series algorithm https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#P-series For doctests run following command: python -m doctest -v p_series.py or python3 -m doctest -v p_series.py For manual testing run: python3 p_series.py """ from __future__ import annotations def p_series(nth_term: float | str, power: float | str) -> list[str]: """ Pure Python implementation of P-Series algorithm :return: The P-Series starting from 1 to last (nth) term Examples: >>> p_series(5, 2) ['1', '1 / 4', '1 / 9', '1 / 16', '1 / 25'] >>> p_series(-5, 2) [] >>> p_series(5, -2) ['1', '1 / 0.25', '1 / 0.1111111111111111', '1 / 0.0625', '1 / 0.04'] >>> p_series("", 1000) [''] >>> p_series(0, 0) [] >>> p_series(1, 1) ['1'] """ 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 if __name__ == "__main__": import doctest doctest.testmod() nth_term = int(input("Enter the last number (nth term) of the P-Series")) power = int(input("Enter the power for P-Series")) print("Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p") print(p_series(nth_term, power))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/series/harmonic_series.py
maths/series/harmonic_series.py
""" This is a pure Python implementation of the Harmonic Series algorithm https://en.wikipedia.org/wiki/Harmonic_series_(mathematics) For doctests run following command: python -m doctest -v harmonic_series.py or python3 -m doctest -v harmonic_series.py For manual testing run: python3 harmonic_series.py """ def harmonic_series(n_term: str) -> list: """Pure Python implementation of Harmonic Series algorithm :param n_term: The last (nth) term of Harmonic Series :return: The Harmonic Series starting from 1 to last (nth) term Examples: >>> harmonic_series(5) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(5.0) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(5.1) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(-5) [] >>> harmonic_series(0) [] >>> harmonic_series(1) ['1'] """ 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 if __name__ == "__main__": nth_term = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/series/geometric.py
maths/series/geometric.py
""" Geometric Mean Reference : https://en.wikipedia.org/wiki/Geometric_mean Geometric series Reference: https://en.wikipedia.org/wiki/Geometric_series """ def is_geometric_series(series: list) -> bool: """ checking whether the input series is geometric series or not >>> is_geometric_series([2, 4, 8]) True >>> is_geometric_series([3, 6, 12, 24]) True >>> is_geometric_series([1, 2, 3]) False >>> is_geometric_series([0, 0, 3]) False >>> is_geometric_series([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list >>> is_geometric_series(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 8] """ 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 def geometric_mean(series: list) -> float: """ return the geometric mean of series >>> geometric_mean([2, 4, 8]) 3.9999999999999996 >>> geometric_mean([3, 6, 12, 24]) 8.48528137423857 >>> geometric_mean([4, 8, 16]) 7.999999999999999 >>> geometric_mean(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 8] >>> geometric_mean([1, 2, 3]) 1.8171205928321397 >>> geometric_mean([0, 2, 3]) 0.0 >>> geometric_mean([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ 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)) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/series/__init__.py
maths/series/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/series/harmonic.py
maths/series/harmonic.py
""" Harmonic mean Reference: https://en.wikipedia.org/wiki/Harmonic_mean Harmonic series Reference: https://en.wikipedia.org/wiki/Harmonic_series(mathematics) """ def is_harmonic_series(series: list) -> bool: """ checking whether the input series is arithmetic series or not >>> is_harmonic_series([ 1, 2/3, 1/2, 2/5, 1/3]) True >>> is_harmonic_series([ 1, 2/3, 2/5, 1/3]) False >>> is_harmonic_series([1, 2, 3]) False >>> is_harmonic_series([1/2, 1/3, 1/4]) True >>> is_harmonic_series([2/5, 2/10, 2/15, 2/20, 2/25]) True >>> is_harmonic_series(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [1, 2/3, 2] >>> is_harmonic_series([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list >>> is_harmonic_series([0]) Traceback (most recent call last): ... ValueError: Input series cannot have 0 as an element >>> is_harmonic_series([1,2,0,6]) Traceback (most recent call last): ... ValueError: Input series cannot have 0 as an element """ 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(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 def harmonic_mean(series: list) -> float: """ return the harmonic mean of series >>> harmonic_mean([1, 4, 4]) 2.0 >>> harmonic_mean([3, 6, 9, 12]) 5.759999999999999 >>> harmonic_mean(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> harmonic_mean([1, 2, 3]) 1.6363636363636365 >>> harmonic_mean([]) Traceback (most recent call last): ... ValueError: Input list must be a non empty list """ 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 if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/series/hexagonal_numbers.py
maths/series/hexagonal_numbers.py
""" A hexagonal number sequence is a sequence of figurate numbers where the nth hexagonal number hₙ is the number of distinct dots in a pattern of dots consisting of the outlines of regular hexagons with sides up to n dots, when the hexagons are overlaid so that they share one vertex. Calculates the hexagonal numbers sequence with a formula hₙ = n(2n-1) where: hₙ --> is nth element of the sequence n --> is the number of element in the sequence reference-->"Hexagonal number" Wikipedia <https://en.wikipedia.org/wiki/Hexagonal_number> """ def hexagonal_numbers(length: int) -> list[int]: """ :param len: max number of elements :type len: int :return: Hexagonal numbers as a list Tests: >>> hexagonal_numbers(10) [0, 1, 6, 15, 28, 45, 66, 91, 120, 153] >>> hexagonal_numbers(5) [0, 1, 6, 15, 28] >>> hexagonal_numbers(0) Traceback (most recent call last): ... ValueError: Length must be a positive integer. """ 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)] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/maths/images/__init__.py
maths/images/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/financial/time_and_half_pay.py
financial/time_and_half_pay.py
""" Calculate time and a half pay """ def pay(hours_worked: float, pay_rate: float, hours: float = 40) -> float: """ hours_worked = The total hours worked pay_rate = Amount of money per hour hours = Number of hours that must be worked before you receive time and a half >>> pay(41, 1) 41.5 >>> pay(65, 19) 1472.5 >>> pay(10, 1) 10.0 """ # Check that all input parameters are float or integer assert isinstance(hours_worked, (float, int)), ( "Parameter 'hours_worked' must be of type 'int' or 'float'" ) assert isinstance(pay_rate, (float, int)), ( "Parameter 'pay_rate' must be of type 'int' or 'float'" ) assert isinstance(hours, (float, int)), ( "Parameter 'hours' must be of type 'int' or 'float'" ) normal_pay = hours_worked * pay_rate over_time = max(0, hours_worked - hours) over_time_pay = over_time * pay_rate / 2 return normal_pay + over_time_pay if __name__ == "__main__": # Test import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/financial/simple_moving_average.py
financial/simple_moving_average.py
""" The Simple Moving Average (SMA) is a statistical calculation used to analyze data points by creating a constantly updated average price over a specific time period. In finance, SMA is often used in time series analysis to smooth out price data and identify trends. Reference: https://en.wikipedia.org/wiki/Moving_average """ from collections.abc import Sequence def simple_moving_average( data: Sequence[float], window_size: int ) -> list[float | None]: """ Calculate the simple moving average (SMA) for some given time series data. :param data: A list of numerical data points. :param window_size: An integer representing the size of the SMA window. :return: A list of SMA values with the same length as the input data. Examples: >>> sma = simple_moving_average([10, 12, 15, 13, 14, 16, 18, 17, 19, 21], 3) >>> [round(value, 2) if value is not None else None for value in sma] [None, None, 12.33, 13.33, 14.0, 14.33, 16.0, 17.0, 18.0, 19.0] >>> simple_moving_average([10, 12, 15], 5) [None, None, None] >>> simple_moving_average([10, 12, 15, 13, 14, 16, 18, 17, 19, 21], 0) Traceback (most recent call last): ... ValueError: Window size must be a positive integer """ if window_size < 1: raise ValueError("Window size must be a positive integer") sma: list[float | None] = [] for i in range(len(data)): if i < window_size - 1: sma.append(None) # SMA not available for early data points else: window = data[i - window_size + 1 : i + 1] sma_value = sum(window) / window_size sma.append(sma_value) return sma if __name__ == "__main__": import doctest doctest.testmod() # Example data (replace with your own time series data) data = [10, 12, 15, 13, 14, 16, 18, 17, 19, 21] # Specify the window size for the SMA window_size = 3 # Calculate the Simple Moving Average sma_values = simple_moving_average(data, window_size) # Print the SMA values print("Simple Moving Average (SMA) Values:") for i, value in enumerate(sma_values): if value is not None: print(f"Day {i + 1}: {value:.2f}") else: print(f"Day {i + 1}: Not enough data for SMA")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/financial/exponential_moving_average.py
financial/exponential_moving_average.py
""" Calculate the exponential moving average (EMA) on the series of stock prices. Wikipedia Reference: https://en.wikipedia.org/wiki/Exponential_smoothing https://www.investopedia.com/terms/e/ema.asp#toc-what-is-an-exponential -moving-average-ema Exponential moving average is used in finance to analyze changes stock prices. EMA is used in conjunction with Simple moving average (SMA), EMA reacts to the changes in the value quicker than SMA, which is one of the advantages of using EMA. """ from collections.abc import Iterator def exponential_moving_average( stock_prices: Iterator[float], window_size: int ) -> Iterator[float]: """ Yields exponential moving averages of the given stock prices. >>> tuple(exponential_moving_average(iter([2, 5, 3, 8.2, 6, 9, 10]), 3)) (2, 3.5, 3.25, 5.725, 5.8625, 7.43125, 8.715625) :param stock_prices: A stream of stock prices :param window_size: The number of stock prices that will trigger a new calculation of the exponential average (window_size > 0) :return: Yields a sequence of exponential moving averages Formula: st = alpha * xt + (1 - alpha) * st_prev Where, st : Exponential moving average at timestamp t xt : stock price in from the stock prices at timestamp t st_prev : Exponential moving average at timestamp t-1 alpha : 2/(1 + window_size) - smoothing factor Exponential moving average (EMA) is a rule of thumb technique for smoothing time series data using an exponential window function. """ if window_size <= 0: raise ValueError("window_size must be > 0") # Calculating smoothing factor alpha = 2 / (1 + window_size) # Exponential average at timestamp t moving_average = 0.0 for i, stock_price in enumerate(stock_prices): if i <= window_size: # Assigning simple moving average till the window_size for the first time # is reached moving_average = (moving_average + stock_price) * 0.5 if i else stock_price else: # Calculating exponential moving average based on current timestamp data # point and previous exponential average value moving_average = (alpha * stock_price) + ((1 - alpha) * moving_average) yield moving_average if __name__ == "__main__": import doctest doctest.testmod() stock_prices = [2.0, 5, 3, 8.2, 6, 9, 10] window_size = 3 result = tuple(exponential_moving_average(iter(stock_prices), window_size)) print(f"{stock_prices = }") print(f"{window_size = }") print(f"{result = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/financial/present_value.py
financial/present_value.py
""" Reference: https://www.investopedia.com/terms/p/presentvalue.asp An algorithm that calculates the present value of a stream of yearly cash flows given... 1. The discount rate (as a decimal, not a percent) 2. An array of cash flows, with the index of the cash flow being the associated year Note: This algorithm assumes that cash flows are paid at the end of the specified year """ def present_value(discount_rate: float, cash_flows: list[float]) -> float: """ >>> present_value(0.13, [10, 20.70, -293, 297]) 4.69 >>> present_value(0.07, [-109129.39, 30923.23, 15098.93, 29734,39]) -42739.63 >>> present_value(0.07, [109129.39, 30923.23, 15098.93, 29734,39]) 175519.15 >>> present_value(-1, [109129.39, 30923.23, 15098.93, 29734,39]) Traceback (most recent call last): ... ValueError: Discount rate cannot be negative >>> present_value(0.03, []) Traceback (most recent call last): ... ValueError: Cash flows list cannot be empty """ if discount_rate < 0: raise ValueError("Discount rate cannot be negative") if not cash_flows: raise ValueError("Cash flows list cannot be empty") present_value = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(cash_flows) ) return round(present_value, ndigits=2) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/financial/price_plus_tax.py
financial/price_plus_tax.py
""" Calculate price plus tax of a good or service given its price and a tax rate. """ def price_plus_tax(price: float, tax_rate: float) -> float: """ >>> price_plus_tax(100, 0.25) 125.0 >>> price_plus_tax(125.50, 0.05) 131.775 """ return price * (1 + tax_rate) if __name__ == "__main__": print(f"{price_plus_tax(100, 0.25) = }") print(f"{price_plus_tax(125.50, 0.05) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/financial/equated_monthly_installments.py
financial/equated_monthly_installments.py
""" Program to calculate the amortization amount per month, given - Principal borrowed - Rate of interest per annum - Years to repay the loan Wikipedia Reference: https://en.wikipedia.org/wiki/Equated_monthly_installment """ def equated_monthly_installments( principal: float, rate_per_annum: float, years_to_repay: int ) -> float: """ Formula for amortization amount per month: A = p * r * (1 + r)^n / ((1 + r)^n - 1) where p is the principal, r is the rate of interest per month and n is the number of payments >>> equated_monthly_installments(25000, 0.12, 3) 830.3577453212793 >>> equated_monthly_installments(25000, 0.12, 10) 358.67737100646826 >>> equated_monthly_installments(0, 0.12, 3) Traceback (most recent call last): ... Exception: Principal borrowed must be > 0 >>> equated_monthly_installments(25000, -1, 3) Traceback (most recent call last): ... Exception: Rate of interest must be >= 0 >>> equated_monthly_installments(25000, 0.12, 0) Traceback (most recent call last): ... Exception: Years to repay must be an integer > 0 """ if principal <= 0: raise Exception("Principal borrowed must be > 0") if rate_per_annum < 0: raise Exception("Rate of interest must be >= 0") if years_to_repay <= 0 or not isinstance(years_to_repay, int): raise Exception("Years to repay must be an integer > 0") # Yearly rate is divided by 12 to get monthly rate rate_per_month = rate_per_annum / 12 # Years to repay is multiplied by 12 to get number of payments as payment is monthly number_of_payments = years_to_repay * 12 return ( principal * rate_per_month * (1 + rate_per_month) ** number_of_payments / ((1 + rate_per_month) ** number_of_payments - 1) ) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/financial/__init__.py
financial/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/financial/straight_line_depreciation.py
financial/straight_line_depreciation.py
""" In accounting, depreciation refers to the decreases in the value of a fixed asset during the asset's useful life. When an organization purchases a fixed asset, the purchase expenditure is not recognized as an expense immediately. Instead, the decreases in the asset's value are recognized as expenses over the years during which the asset is used. The following methods are widely used for depreciation calculation in accounting: - Straight-line method - Diminishing balance method - Units-of-production method The straight-line method is the simplest and most widely used. This method calculates depreciation by spreading the cost evenly over the asset's useful life. The following formula shows how to calculate the yearly depreciation expense: - annual depreciation expense = (purchase cost of asset - residual value) / useful life of asset(years) Further information on: https://en.wikipedia.org/wiki/Depreciation The function, straight_line_depreciation, returns a list of the depreciation expenses over the given period. """ def straight_line_depreciation( useful_years: int, purchase_value: float, residual_value: float = 0.0, ) -> list[float]: """ Calculate the depreciation expenses over the given period :param useful_years: Number of years the asset will be used :param purchase_value: Purchase expenditure for the asset :param residual_value: Residual value of the asset at the end of its useful life :return: A list of annual depreciation expenses over the asset's useful life >>> straight_line_depreciation(10, 1100.0, 100.0) [100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0] >>> straight_line_depreciation(6, 1250.0, 50.0) [200.0, 200.0, 200.0, 200.0, 200.0, 200.0] >>> straight_line_depreciation(4, 1001.0) [250.25, 250.25, 250.25, 250.25] >>> straight_line_depreciation(11, 380.0, 50.0) [30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0] >>> straight_line_depreciation(1, 4985, 100) [4885.0] """ if not isinstance(useful_years, int): raise TypeError("Useful years must be an integer") if useful_years < 1: raise ValueError("Useful years cannot be less than 1") if not isinstance(purchase_value, (float, int)): raise TypeError("Purchase value must be numeric") if not isinstance(residual_value, (float, int)): raise TypeError("Residual value must be numeric") if purchase_value < 0.0: raise ValueError("Purchase value cannot be less than zero") if purchase_value < residual_value: raise ValueError("Purchase value cannot be less than residual value") # Calculate annual depreciation expense depreciable_cost = purchase_value - residual_value annual_depreciation_expense = depreciable_cost / useful_years # List of annual depreciation expenses list_of_depreciation_expenses = [] accumulated_depreciation_expense = 0.0 for period in range(useful_years): if period != useful_years - 1: accumulated_depreciation_expense += annual_depreciation_expense list_of_depreciation_expenses.append(annual_depreciation_expense) else: depreciation_expense_in_end_year = ( depreciable_cost - accumulated_depreciation_expense ) list_of_depreciation_expenses.append(depreciation_expense_in_end_year) return list_of_depreciation_expenses if __name__ == "__main__": user_input_useful_years = int(input("Please Enter Useful Years:\n > ")) user_input_purchase_value = float(input("Please Enter Purchase Value:\n > ")) user_input_residual_value = float(input("Please Enter Residual Value:\n > ")) print( straight_line_depreciation( user_input_useful_years, user_input_purchase_value, user_input_residual_value, ) )
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/financial/interest.py
financial/interest.py
# https://www.investopedia.com from __future__ import annotations def simple_interest( principal: float, daily_interest_rate: float, days_between_payments: float ) -> float: """ >>> simple_interest(18000.0, 0.06, 3) 3240.0 >>> simple_interest(0.5, 0.06, 3) 0.09 >>> simple_interest(18000.0, 0.01, 10) 1800.0 >>> simple_interest(18000.0, 0.0, 3) 0.0 >>> simple_interest(5500.0, 0.01, 100) 5500.0 >>> simple_interest(10000.0, -0.06, 3) Traceback (most recent call last): ... ValueError: daily_interest_rate must be >= 0 >>> simple_interest(-10000.0, 0.06, 3) Traceback (most recent call last): ... ValueError: principal must be > 0 >>> simple_interest(5500.0, 0.01, -5) Traceback (most recent call last): ... ValueError: days_between_payments must be > 0 """ if days_between_payments <= 0: raise ValueError("days_between_payments must be > 0") if daily_interest_rate < 0: raise ValueError("daily_interest_rate must be >= 0") if principal <= 0: raise ValueError("principal must be > 0") return principal * daily_interest_rate * days_between_payments def compound_interest( principal: float, nominal_annual_interest_rate_percentage: float, number_of_compounding_periods: float, ) -> float: """ >>> compound_interest(10000.0, 0.05, 3) 1576.2500000000014 >>> compound_interest(10000.0, 0.05, 1) 500.00000000000045 >>> compound_interest(0.5, 0.05, 3) 0.07881250000000006 >>> compound_interest(10000.0, 0.06, -4) Traceback (most recent call last): ... ValueError: number_of_compounding_periods must be > 0 >>> compound_interest(10000.0, -3.5, 3.0) Traceback (most recent call last): ... ValueError: nominal_annual_interest_rate_percentage must be >= 0 >>> compound_interest(-5500.0, 0.01, 5) Traceback (most recent call last): ... ValueError: principal must be > 0 """ if number_of_compounding_periods <= 0: raise ValueError("number_of_compounding_periods must be > 0") if nominal_annual_interest_rate_percentage < 0: raise ValueError("nominal_annual_interest_rate_percentage must be >= 0") if principal <= 0: raise ValueError("principal must be > 0") return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def apr_interest( principal: float, nominal_annual_percentage_rate: float, number_of_years: float, ) -> float: """ >>> apr_interest(10000.0, 0.05, 3) 1618.223072263547 >>> apr_interest(10000.0, 0.05, 1) 512.6749646744732 >>> apr_interest(0.5, 0.05, 3) 0.08091115361317736 >>> apr_interest(10000.0, 0.06, -4) Traceback (most recent call last): ... ValueError: number_of_years must be > 0 >>> apr_interest(10000.0, -3.5, 3.0) Traceback (most recent call last): ... ValueError: nominal_annual_percentage_rate must be >= 0 >>> apr_interest(-5500.0, 0.01, 5) Traceback (most recent call last): ... ValueError: principal must be > 0 """ if number_of_years <= 0: raise ValueError("number_of_years must be > 0") if nominal_annual_percentage_rate < 0: raise ValueError("nominal_annual_percentage_rate must be >= 0") if principal <= 0: raise ValueError("principal must be > 0") return compound_interest( principal, nominal_annual_percentage_rate / 365, number_of_years * 365 ) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/neural_network/convolution_neural_network.py
neural_network/convolution_neural_network.py
""" - - - - - -- - - - - - - - - - - - - - - - - - - - - - - Name - - CNN - Convolution Neural Network For Photo Recognizing Goal - - Recognize Handwriting Word Photo Detail: Total 5 layers neural network * Convolution layer * Pooling layer * Input layer layer of BP * Hidden layer of BP * Output layer of BP Author: Stephen Lee Github: 245885195@qq.com Date: 2017.9.20 - - - - - -- - - - - - - - - - - - - - - - - - - - - - - """ import pickle import numpy as np from matplotlib import pyplot as plt class CNN: def __init__( self, conv1_get, size_p1, bp_num1, bp_num2, bp_num3, rate_w=0.2, rate_t=0.2 ): """ :param conv1_get: [a,c,d], size, number, step of convolution kernel :param size_p1: pooling size :param bp_num1: units number of flatten layer :param bp_num2: units number of hidden layer :param bp_num3: units number of output layer :param rate_w: rate of weight learning :param rate_t: rate of threshold learning """ self.num_bp1 = bp_num1 self.num_bp2 = bp_num2 self.num_bp3 = bp_num3 self.conv1 = conv1_get[:2] self.step_conv1 = conv1_get[2] self.size_pooling1 = size_p1 self.rate_weight = rate_w self.rate_thre = rate_t rng = np.random.default_rng() self.w_conv1 = [ np.asmatrix(-1 * rng.random((self.conv1[0], self.conv1[0])) + 0.5) for i in range(self.conv1[1]) ] self.wkj = np.asmatrix(-1 * rng.random((self.num_bp3, self.num_bp2)) + 0.5) self.vji = np.asmatrix(-1 * rng.random((self.num_bp2, self.num_bp1)) + 0.5) self.thre_conv1 = -2 * rng.random(self.conv1[1]) + 1 self.thre_bp2 = -2 * rng.random(self.num_bp2) + 1 self.thre_bp3 = -2 * rng.random(self.num_bp3) + 1 def save_model(self, save_path): # save model dict with pickle model_dic = { "num_bp1": self.num_bp1, "num_bp2": self.num_bp2, "num_bp3": self.num_bp3, "conv1": self.conv1, "step_conv1": self.step_conv1, "size_pooling1": self.size_pooling1, "rate_weight": self.rate_weight, "rate_thre": self.rate_thre, "w_conv1": self.w_conv1, "wkj": self.wkj, "vji": self.vji, "thre_conv1": self.thre_conv1, "thre_bp2": self.thre_bp2, "thre_bp3": self.thre_bp3, } with open(save_path, "wb") as f: pickle.dump(model_dic, f) print(f"Model saved: {save_path}") @classmethod def read_model(cls, model_path): # read saved model with open(model_path, "rb") as f: model_dic = pickle.load(f) # noqa: S301 conv_get = model_dic.get("conv1") conv_get.append(model_dic.get("step_conv1")) size_p1 = model_dic.get("size_pooling1") bp1 = model_dic.get("num_bp1") bp2 = model_dic.get("num_bp2") bp3 = model_dic.get("num_bp3") r_w = model_dic.get("rate_weight") r_t = model_dic.get("rate_thre") # create model instance conv_ins = CNN(conv_get, size_p1, bp1, bp2, bp3, r_w, r_t) # modify model parameter conv_ins.w_conv1 = model_dic.get("w_conv1") conv_ins.wkj = model_dic.get("wkj") conv_ins.vji = model_dic.get("vji") conv_ins.thre_conv1 = model_dic.get("thre_conv1") conv_ins.thre_bp2 = model_dic.get("thre_bp2") conv_ins.thre_bp3 = model_dic.get("thre_bp3") return conv_ins def sig(self, x): return 1 / (1 + np.exp(-1 * x)) def do_round(self, x): return round(x, 3) def convolute(self, data, convs, w_convs, thre_convs, conv_step): # convolution process size_conv = convs[0] num_conv = convs[1] size_data = np.shape(data)[0] # get the data slice of original image data, data_focus data_focus = [] for i_focus in range(0, size_data - size_conv + 1, conv_step): for j_focus in range(0, size_data - size_conv + 1, conv_step): focus = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(focus) # calculate the feature map of every single kernel, and saved as list of matrix data_featuremap = [] size_feature_map = int((size_data - size_conv) / conv_step + 1) for i_map in range(num_conv): featuremap = [] for i_focus in range(len(data_focus)): net_focus = ( np.sum(np.multiply(data_focus[i_focus], w_convs[i_map])) - thre_convs[i_map] ) featuremap.append(self.sig(net_focus)) featuremap = np.asmatrix(featuremap).reshape( size_feature_map, size_feature_map ) data_featuremap.append(featuremap) # expanding the data slice to one dimension focus1_list = [] for each_focus in data_focus: focus1_list.extend(self.Expand_Mat(each_focus)) focus_list = np.asarray(focus1_list) return focus_list, data_featuremap def pooling(self, featuremaps, size_pooling, pooling_type="average_pool"): # pooling process size_map = len(featuremaps[0]) size_pooled = int(size_map / size_pooling) featuremap_pooled = [] for i_map in range(len(featuremaps)): feature_map = featuremaps[i_map] map_pooled = [] for i_focus in range(0, size_map, size_pooling): for j_focus in range(0, size_map, size_pooling): focus = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(focus)) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(focus)) map_pooled = np.asmatrix(map_pooled).reshape(size_pooled, size_pooled) featuremap_pooled.append(map_pooled) return featuremap_pooled def _expand(self, data): # expanding three dimension data to one dimension list data_expanded = [] for i in range(len(data)): shapes = np.shape(data[i]) data_listed = data[i].reshape(1, shapes[0] * shapes[1]) data_listed = data_listed.getA().tolist()[0] data_expanded.extend(data_listed) data_expanded = np.asarray(data_expanded) return data_expanded def _expand_mat(self, data_mat): # expanding matrix to one dimension list data_mat = np.asarray(data_mat) shapes = np.shape(data_mat) data_expanded = data_mat.reshape(1, shapes[0] * shapes[1]) return data_expanded def _calculate_gradient_from_pool( self, out_map, pd_pool, num_map, size_map, size_pooling ): """ calculate the gradient from the data slice of pool layer pd_pool: list of matrix out_map: the shape of data slice(size_map*size_map) return: pd_all: list of matrix, [num, size_map, size_map] """ pd_all = [] i_pool = 0 for i_map in range(num_map): pd_conv1 = np.ones((size_map, size_map)) for i in range(0, size_map, size_pooling): for j in range(0, size_map, size_pooling): pd_conv1[i : i + size_pooling, j : j + size_pooling] = pd_pool[ i_pool ] i_pool = i_pool + 1 pd_conv2 = np.multiply( pd_conv1, np.multiply(out_map[i_map], (1 - out_map[i_map])) ) pd_all.append(pd_conv2) return pd_all def train( self, patterns, datas_train, datas_teach, n_repeat, error_accuracy, draw_e=bool ): # model training print("----------------------Start Training-------------------------") print((" - - Shape: Train_Data ", np.shape(datas_train))) print((" - - Shape: Teach_Data ", np.shape(datas_teach))) rp = 0 all_mse = [] mse = 10000 while rp < n_repeat and mse >= error_accuracy: error_count = 0 print(f"-------------Learning Time {rp}--------------") for p in range(len(datas_train)): # print('------------Learning Image: %d--------------'%p) data_train = np.asmatrix(datas_train[p]) data_teach = np.asarray(datas_teach[p]) data_focus1, data_conved1 = self.convolute( data_train, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) shape_featuremap1 = np.shape(data_conved1) """ print(' -----original shape ', np.shape(data_train)) print(' ---- after convolution ',np.shape(data_conv1)) print(' -----after pooling ',np.shape(data_pooled1)) """ data_bp_input = self._expand(data_pooled1) bp_out1 = data_bp_input bp_net_j = np.dot(bp_out1, self.vji.T) - self.thre_bp2 bp_out2 = self.sig(bp_net_j) bp_net_k = np.dot(bp_out2, self.wkj.T) - self.thre_bp3 bp_out3 = self.sig(bp_net_k) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- pd_k_all = np.multiply( (data_teach - bp_out3), np.multiply(bp_out3, (1 - bp_out3)) ) pd_j_all = np.multiply( np.dot(pd_k_all, self.wkj), np.multiply(bp_out2, (1 - bp_out2)) ) pd_i_all = np.dot(pd_j_all, self.vji) pd_conv1_pooled = pd_i_all / (self.size_pooling1 * self.size_pooling1) pd_conv1_pooled = pd_conv1_pooled.T.getA().tolist() pd_conv1_all = self._calculate_gradient_from_pool( data_conved1, pd_conv1_pooled, shape_featuremap1[0], shape_featuremap1[1], self.size_pooling1, ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conv1[1]): pd_conv_list = self._expand_mat(pd_conv1_all[k_conv]) delta_w = self.rate_weight * np.dot(pd_conv_list, data_focus1) self.w_conv1[k_conv] = self.w_conv1[k_conv] + delta_w.reshape( (self.conv1[0], self.conv1[0]) ) self.thre_conv1[k_conv] = ( self.thre_conv1[k_conv] - np.sum(pd_conv1_all[k_conv]) * self.rate_thre ) # all connected layer self.wkj = self.wkj + pd_k_all.T * bp_out2 * self.rate_weight self.vji = self.vji + pd_j_all.T * bp_out1 * self.rate_weight self.thre_bp3 = self.thre_bp3 - pd_k_all * self.rate_thre self.thre_bp2 = self.thre_bp2 - pd_j_all * self.rate_thre # calculate the sum error of all single image errors = np.sum(abs(data_teach - bp_out3)) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) rp = rp + 1 mse = error_count / patterns all_mse.append(mse) def draw_error(): yplot = [error_accuracy for i in range(int(n_repeat * 1.2))] plt.plot(all_mse, "+-") plt.plot(yplot, "r--") plt.xlabel("Learning Times") plt.ylabel("All_mse") plt.grid(True, alpha=0.5) plt.show() print("------------------Training Complete---------------------") print((" - - Training epoch: ", rp, f" - - Mse: {mse:.6f}")) if draw_e: draw_error() return mse def predict(self, datas_test): # model predict produce_out = [] print("-------------------Start Testing-------------------------") print((" - - Shape: Test_Data ", np.shape(datas_test))) for p in range(len(datas_test)): data_test = np.asmatrix(datas_test[p]) _data_focus1, data_conved1 = self.convolute( data_test, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) data_bp_input = self._expand(data_pooled1) bp_out1 = data_bp_input bp_net_j = bp_out1 * self.vji.T - self.thre_bp2 bp_out2 = self.sig(bp_net_j) bp_net_k = bp_out2 * self.wkj.T - self.thre_bp3 bp_out3 = self.sig(bp_net_k) produce_out.extend(bp_out3.getA().tolist()) res = [list(map(self.do_round, each)) for each in produce_out] return np.asarray(res) def convolution(self, data): # return the data of image after convoluting process so we can check it out data_test = np.asmatrix(data) _data_focus1, data_conved1 = self.convolute( data_test, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) return data_conved1, data_pooled1 if __name__ == "__main__": """ I will put the example in another file """
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/neural_network/simple_neural_network.py
neural_network/simple_neural_network.py
""" Forward propagation explanation: https://towardsdatascience.com/forward-propagation-in-neural-networks-simplified-math-and-code-version-bbcfef6f9250 """ import math import random # Sigmoid def sigmoid_function(value: float, deriv: bool = False) -> float: """Return the sigmoid function of a float. >>> sigmoid_function(3.5) 0.9706877692486436 >>> sigmoid_function(3.5, True) -8.75 """ if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value)) # Initial Value INITIAL_VALUE = 0.02 def forward_propagation(expected: int, number_propagations: int) -> float: """Return the value found after the forward propagation training. >>> res = forward_propagation(32, 450_000) # Was 10_000_000 >>> res > 31 and res < 33 True >>> res = forward_propagation(32, 1000) >>> res > 31 and res < 33 False """ # Random weight weight = float(2 * (random.randint(1, 100)) - 1) for _ in range(number_propagations): # Forward propagation layer_1 = sigmoid_function(INITIAL_VALUE * weight) # How much did we miss? layer_1_error = (expected / 100) - layer_1 # Error delta layer_1_delta = layer_1_error * sigmoid_function(layer_1, True) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_1 * 100 if __name__ == "__main__": import doctest doctest.testmod() expected = int(input("Expected value: ")) number_propagations = int(input("Number of propagations: ")) print(forward_propagation(expected, number_propagations))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/neural_network/input_data.py
neural_network/input_data.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functions for downloading and reading MNIST data (deprecated). This module and all its submodules are deprecated. """ import gzip import os import typing import urllib import numpy as np from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated class _Datasets(typing.NamedTuple): train: "_DataSet" validation: "_DataSet" test: "_DataSet" # CVDF mirror of http://yann.lecun.com/exdb/mnist/ DEFAULT_SOURCE_URL = "https://storage.googleapis.com/cvdf-datasets/mnist/" def _read32(bytestream): dt = np.dtype(np.uint32).newbyteorder(">") return np.frombuffer(bytestream.read(4), dtype=dt)[0] @deprecated(None, "Please use tf.data to implement this functionality.") def _extract_images(f): """Extract the images into a 4D uint8 numpy array [index, y, x, depth]. Args: f: A file object that can be passed into a gzip reader. Returns: data: A 4D uint8 numpy array [index, y, x, depth]. Raises: ValueError: If the bytestream does not start with 2051. """ print("Extracting", f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) if magic != 2051: msg = f"Invalid magic number {magic} in MNIST image file: {f.name}" raise ValueError(msg) num_images = _read32(bytestream) rows = _read32(bytestream) cols = _read32(bytestream) buf = bytestream.read(rows * cols * num_images) data = np.frombuffer(buf, dtype=np.uint8) data = data.reshape(num_images, rows, cols, 1) return data @deprecated(None, "Please use tf.one_hot on tensors.") def _dense_to_one_hot(labels_dense, num_classes): """Convert class labels from scalars to one-hot vectors.""" num_labels = labels_dense.shape[0] index_offset = np.arange(num_labels) * num_classes labels_one_hot = np.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 return labels_one_hot @deprecated(None, "Please use tf.data to implement this functionality.") def _extract_labels(f, one_hot=False, num_classes=10): """Extract the labels into a 1D uint8 numpy array [index]. Args: f: A file object that can be passed into a gzip reader. one_hot: Does one hot encoding for the result. num_classes: Number of classes for the one hot encoding. Returns: labels: a 1D uint8 numpy array. Raises: ValueError: If the bystream doesn't start with 2049. """ print("Extracting", f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) if magic != 2049: msg = f"Invalid magic number {magic} in MNIST label file: {f.name}" raise ValueError(msg) num_items = _read32(bytestream) buf = bytestream.read(num_items) labels = np.frombuffer(buf, dtype=np.uint8) if one_hot: return _dense_to_one_hot(labels, num_classes) return labels class _DataSet: """Container class for a _DataSet (deprecated). THIS CLASS IS DEPRECATED. """ @deprecated( None, "Please use alternatives such as official/mnist/_DataSet.py" " from tensorflow/models.", ) def __init__( self, images, labels, fake_data=False, one_hot=False, dtype=dtypes.float32, reshape=True, seed=None, ): """Construct a _DataSet. one_hot arg is used only if fake_data is true. `dtype` can be either `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into `[0, 1]`. Seed arg provides for convenient deterministic testing. Args: images: The images labels: The labels fake_data: Ignore inages and labels, use fake data. one_hot: Bool, return the labels as one hot vectors (if True) or ints (if False). dtype: Output image dtype. One of [uint8, float32]. `uint8` output has range [0,255]. float32 output has range [0,1]. reshape: Bool. If True returned images are returned flattened to vectors. seed: The random seed to use. """ seed1, seed2 = random_seed.get_seed(seed) # If op level seed is not set, use whatever graph level seed is returned self._rng = np.random.default_rng(seed1 if seed is None else seed2) dtype = dtypes.as_dtype(dtype).base_dtype if dtype not in (dtypes.uint8, dtypes.float32): msg = f"Invalid image dtype {dtype!r}, expected uint8 or float32" raise TypeError(msg) if fake_data: self._num_examples = 10000 self.one_hot = one_hot else: assert images.shape[0] == labels.shape[0], ( f"images.shape: {images.shape} labels.shape: {labels.shape}" ) self._num_examples = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 images = images.reshape( images.shape[0], images.shape[1] * images.shape[2] ) if dtype == dtypes.float32: # Convert from [0, 255] -> [0.0, 1.0]. images = images.astype(np.float32) images = np.multiply(images, 1.0 / 255.0) self._images = images self._labels = labels self._epochs_completed = 0 self._index_in_epoch = 0 @property def images(self): return self._images @property def labels(self): return self._labels @property def num_examples(self): return self._num_examples @property def epochs_completed(self): return self._epochs_completed def next_batch(self, batch_size, fake_data=False, shuffle=True): """Return the next `batch_size` examples from this data set.""" if fake_data: fake_image = [1] * 784 fake_label = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(batch_size)], [fake_label for _ in range(batch_size)], ) start = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: perm0 = np.arange(self._num_examples) self._rng.shuffle(perm0) self._images = self.images[perm0] self._labels = self.labels[perm0] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch rest_num_examples = self._num_examples - start images_rest_part = self._images[start : self._num_examples] labels_rest_part = self._labels[start : self._num_examples] # Shuffle the data if shuffle: perm = np.arange(self._num_examples) self._rng.shuffle(perm) self._images = self.images[perm] self._labels = self.labels[perm] # Start next epoch start = 0 self._index_in_epoch = batch_size - rest_num_examples end = self._index_in_epoch images_new_part = self._images[start:end] labels_new_part = self._labels[start:end] return ( np.concatenate((images_rest_part, images_new_part), axis=0), np.concatenate((labels_rest_part, labels_new_part), axis=0), ) else: self._index_in_epoch += batch_size end = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(None, "Please write your own downloading logic.") def _maybe_download(filename, work_directory, source_url): """Download the data from source url, unless it's already here. Args: filename: string, name of the file in the directory. work_directory: string, path to working directory. source_url: url to download from if file doesn't exist. Returns: Path to resulting file. """ if not gfile.Exists(work_directory): gfile.MakeDirs(work_directory) filepath = os.path.join(work_directory, filename) if not gfile.Exists(filepath): urllib.request.urlretrieve(source_url, filepath) # noqa: S310 with gfile.GFile(filepath) as f: size = f.size() print("Successfully downloaded", filename, size, "bytes.") return filepath @deprecated(None, "Please use alternatives such as: tensorflow_datasets.load('mnist')") def read_data_sets( train_dir, fake_data=False, one_hot=False, dtype=dtypes.float32, reshape=True, validation_size=5000, seed=None, source_url=DEFAULT_SOURCE_URL, ): if fake_data: def fake(): return _DataSet( [], [], fake_data=True, one_hot=one_hot, dtype=dtype, seed=seed ) train = fake() validation = fake() test = fake() return _Datasets(train=train, validation=validation, test=test) if not source_url: # empty string check source_url = DEFAULT_SOURCE_URL train_images_file = "train-images-idx3-ubyte.gz" train_labels_file = "train-labels-idx1-ubyte.gz" test_images_file = "t10k-images-idx3-ubyte.gz" test_labels_file = "t10k-labels-idx1-ubyte.gz" local_file = _maybe_download( train_images_file, train_dir, source_url + train_images_file ) with gfile.Open(local_file, "rb") as f: train_images = _extract_images(f) local_file = _maybe_download( train_labels_file, train_dir, source_url + train_labels_file ) with gfile.Open(local_file, "rb") as f: train_labels = _extract_labels(f, one_hot=one_hot) local_file = _maybe_download( test_images_file, train_dir, source_url + test_images_file ) with gfile.Open(local_file, "rb") as f: test_images = _extract_images(f) local_file = _maybe_download( test_labels_file, train_dir, source_url + test_labels_file ) with gfile.Open(local_file, "rb") as f: test_labels = _extract_labels(f, one_hot=one_hot) if not 0 <= validation_size <= len(train_images): msg = ( "Validation size should be between 0 and " f"{len(train_images)}. Received: {validation_size}." ) raise ValueError(msg) validation_images = train_images[:validation_size] validation_labels = train_labels[:validation_size] train_images = train_images[validation_size:] train_labels = train_labels[validation_size:] options = {"dtype": dtype, "reshape": reshape, "seed": seed} train = _DataSet(train_images, train_labels, **options) validation = _DataSet(validation_images, validation_labels, **options) test = _DataSet(test_images, test_labels, **options) return _Datasets(train=train, validation=validation, test=test)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/neural_network/__init__.py
neural_network/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/neural_network/back_propagation_neural_network.py
neural_network/back_propagation_neural_network.py
#!/usr/bin/python """ A Framework of Back Propagation Neural Network (BP) model Easy to use: * add many layers as you want ! ! ! * clearly see how the loss decreasing Easy to expand: * more activation functions * more loss functions * more optimization method Author: Stephen Lee Github : https://github.com/RiptideBo Date: 2017.11.23 """ import numpy as np from matplotlib import pyplot as plt def sigmoid(x: np.ndarray) -> np.ndarray: return 1 / (1 + np.exp(-x)) class DenseLayer: """ Layers of BP neural network """ def __init__( self, units, activation=None, learning_rate=None, is_input_layer=False ): """ common connected layer of bp network :param units: numbers of neural units :param activation: activation function :param learning_rate: learning rate for paras :param is_input_layer: whether it is input layer or not """ self.units = units self.weight = None self.bias = None self.activation = activation if learning_rate is None: learning_rate = 0.3 self.learn_rate = learning_rate self.is_input_layer = is_input_layer def initializer(self, back_units): rng = np.random.default_rng() self.weight = np.asmatrix(rng.normal(0, 0.5, (self.units, back_units))) self.bias = np.asmatrix(rng.normal(0, 0.5, self.units)).T if self.activation is None: self.activation = sigmoid def cal_gradient(self): # activation function may be sigmoid or linear if self.activation == sigmoid: gradient_mat = np.dot(self.output, (1 - self.output).T) gradient_activation = np.diag(np.diag(gradient_mat)) else: gradient_activation = 1 return gradient_activation def forward_propagation(self, xdata): self.xdata = xdata if self.is_input_layer: # input layer self.wx_plus_b = xdata self.output = xdata return xdata else: self.wx_plus_b = np.dot(self.weight, self.xdata) - self.bias self.output = self.activation(self.wx_plus_b) return self.output def back_propagation(self, gradient): gradient_activation = self.cal_gradient() # i * i 维 gradient = np.asmatrix(np.dot(gradient.T, gradient_activation)) self._gradient_weight = np.asmatrix(self.xdata) self._gradient_bias = -1 self._gradient_x = self.weight self.gradient_weight = np.dot(gradient.T, self._gradient_weight.T) self.gradient_bias = gradient * self._gradient_bias self.gradient = np.dot(gradient, self._gradient_x).T # upgrade: the Negative gradient direction self.weight = self.weight - self.learn_rate * self.gradient_weight self.bias = self.bias - self.learn_rate * self.gradient_bias.T # updates the weights and bias according to learning rate (0.3 if undefined) return self.gradient class BPNN: """ Back Propagation Neural Network model """ def __init__(self): self.layers = [] self.train_mse = [] self.fig_loss = plt.figure() self.ax_loss = self.fig_loss.add_subplot(1, 1, 1) def add_layer(self, layer): self.layers.append(layer) def build(self): for i, layer in enumerate(self.layers[:]): if i < 1: layer.is_input_layer = True else: layer.initializer(self.layers[i - 1].units) def summary(self): for i, layer in enumerate(self.layers[:]): print(f"------- layer {i} -------") print("weight.shape ", np.shape(layer.weight)) print("bias.shape ", np.shape(layer.bias)) def train(self, xdata, ydata, train_round, accuracy): self.train_round = train_round self.accuracy = accuracy self.ax_loss.hlines(self.accuracy, 0, self.train_round * 1.1) x_shape = np.shape(xdata) for _ in range(train_round): all_loss = 0 for row in range(x_shape[0]): _xdata = np.asmatrix(xdata[row, :]).T _ydata = np.asmatrix(ydata[row, :]).T # forward propagation for layer in self.layers: _xdata = layer.forward_propagation(_xdata) loss, gradient = self.cal_loss(_ydata, _xdata) all_loss = all_loss + loss # back propagation: the input_layer does not upgrade for layer in self.layers[:0:-1]: gradient = layer.back_propagation(gradient) mse = all_loss / x_shape[0] self.train_mse.append(mse) self.plot_loss() if mse < self.accuracy: print("----达到精度----") return mse return None def cal_loss(self, ydata, ydata_): self.loss = np.sum(np.power((ydata - ydata_), 2)) self.loss_gradient = 2 * (ydata_ - ydata) # vector (shape is the same as _ydata.shape) return self.loss, self.loss_gradient def plot_loss(self): if self.ax_loss.lines: self.ax_loss.lines.remove(self.ax_loss.lines[0]) self.ax_loss.plot(self.train_mse, "r-") plt.ion() plt.xlabel("step") plt.ylabel("loss") plt.show() plt.pause(0.1) def example(): rng = np.random.default_rng() x = rng.normal(size=(10, 10)) y = np.asarray( [ [0.8, 0.4], [0.4, 0.3], [0.34, 0.45], [0.67, 0.32], [0.88, 0.67], [0.78, 0.77], [0.55, 0.66], [0.55, 0.43], [0.54, 0.1], [0.1, 0.5], ] ) model = BPNN() for i in (10, 20, 30, 2): model.add_layer(DenseLayer(i)) model.build() model.summary() model.train(xdata=x, ydata=y, train_round=100, accuracy=0.01) if __name__ == "__main__": example()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/neural_network/two_hidden_layers_neural_network.py
neural_network/two_hidden_layers_neural_network.py
""" References: - http://neuralnetworksanddeeplearning.com/chap2.html (Backpropagation) - https://en.wikipedia.org/wiki/Sigmoid_function (Sigmoid activation function) - https://en.wikipedia.org/wiki/Feedforward_neural_network (Feedforward) """ import numpy as np class TwoHiddenLayerNeuralNetwork: def __init__(self, input_array: np.ndarray, output_array: np.ndarray) -> None: """ This function initializes the TwoHiddenLayerNeuralNetwork class with random weights for every layer and initializes predicted output with zeroes. input_array : input values for training the neural network (i.e training data) . output_array : expected output values of the given inputs. """ # Input values provided for training the model. self.input_array = input_array # Random initial weights are assigned where first argument is the # number of nodes in previous layer and second argument is the # number of nodes in the next layer. # Random initial weights are assigned. # self.input_array.shape[1] is used to represent number of nodes in input layer. # First hidden layer consists of 4 nodes. rng = np.random.default_rng() self.input_layer_and_first_hidden_layer_weights = rng.random( (self.input_array.shape[1], 4) ) # Random initial values for the first hidden layer. # First hidden layer has 4 nodes. # Second hidden layer has 3 nodes. self.first_hidden_layer_and_second_hidden_layer_weights = rng.random((4, 3)) # Random initial values for the second hidden layer. # Second hidden layer has 3 nodes. # Output layer has 1 node. self.second_hidden_layer_and_output_layer_weights = rng.random((3, 1)) # Real output values provided. self.output_array = output_array # Predicted output values by the neural network. # Predicted_output array initially consists of zeroes. self.predicted_output = np.zeros(output_array.shape) def feedforward(self) -> np.ndarray: """ The information moves in only one direction i.e. forward from the input nodes, through the two hidden nodes and to the output nodes. There are no cycles or loops in the network. Return layer_between_second_hidden_layer_and_output (i.e the last layer of the neural network). >>> input_val = np.array(([0, 0, 0], [0, 0, 0], [0, 0, 0]), dtype=float) >>> output_val = np.array(([0], [0], [0]), dtype=float) >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val) >>> res = nn.feedforward() >>> array_sum = np.sum(res) >>> bool(np.isnan(array_sum)) False """ # Layer_between_input_and_first_hidden_layer is the layer connecting the # input nodes with the first hidden layer nodes. self.layer_between_input_and_first_hidden_layer = sigmoid( np.dot(self.input_array, self.input_layer_and_first_hidden_layer_weights) ) # layer_between_first_hidden_layer_and_second_hidden_layer is the layer # connecting the first hidden set of nodes with the second hidden set of nodes. self.layer_between_first_hidden_layer_and_second_hidden_layer = sigmoid( np.dot( self.layer_between_input_and_first_hidden_layer, self.first_hidden_layer_and_second_hidden_layer_weights, ) ) # layer_between_second_hidden_layer_and_output is the layer connecting # second hidden layer with the output node. self.layer_between_second_hidden_layer_and_output = sigmoid( np.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer, self.second_hidden_layer_and_output_layer_weights, ) ) return self.layer_between_second_hidden_layer_and_output def back_propagation(self) -> None: """ Function for fine-tuning the weights of the neural net based on the error rate obtained in the previous epoch (i.e., iteration). Updation is done using derivative of sogmoid activation function. >>> input_val = np.array(([0, 0, 0], [0, 0, 0], [0, 0, 0]), dtype=float) >>> output_val = np.array(([0], [0], [0]), dtype=float) >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val) >>> res = nn.feedforward() >>> nn.back_propagation() >>> updated_weights = nn.second_hidden_layer_and_output_layer_weights >>> bool((res == updated_weights).all()) False """ updated_second_hidden_layer_and_output_layer_weights = np.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T, 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output), ) updated_first_hidden_layer_and_second_hidden_layer_weights = np.dot( self.layer_between_input_and_first_hidden_layer.T, np.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output), self.second_hidden_layer_and_output_layer_weights.T, ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ), ) updated_input_layer_and_first_hidden_layer_weights = np.dot( self.input_array.T, np.dot( np.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output), self.second_hidden_layer_and_output_layer_weights.T, ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ), self.first_hidden_layer_and_second_hidden_layer_weights.T, ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer), ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def train(self, output: np.ndarray, iterations: int, give_loss: bool) -> None: """ Performs the feedforwarding and back propagation process for the given number of iterations. Every iteration will update the weights of neural network. output : real output values,required for calculating loss. iterations : number of times the weights are to be updated. give_loss : boolean value, If True then prints loss for each iteration, If False then nothing is printed >>> input_val = np.array(([0, 0, 0], [0, 1, 0], [0, 0, 1]), dtype=float) >>> output_val = np.array(([0], [1], [1]), dtype=float) >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val) >>> first_iteration_weights = nn.feedforward() >>> nn.back_propagation() >>> updated_weights = nn.second_hidden_layer_and_output_layer_weights >>> bool((first_iteration_weights == updated_weights).all()) False """ for iteration in range(1, iterations + 1): self.output = self.feedforward() self.back_propagation() if give_loss: loss = np.mean(np.square(output - self.feedforward())) print(f"Iteration {iteration} Loss: {loss}") def predict(self, input_arr: np.ndarray) -> int: """ Predict's the output for the given input values using the trained neural network. The output value given by the model ranges in-between 0 and 1. The predict function returns 1 if the model value is greater than the threshold value else returns 0, as the real output values are in binary. >>> input_val = np.array(([0, 0, 0], [0, 1, 0], [0, 0, 1]), dtype=float) >>> output_val = np.array(([0], [1], [1]), dtype=float) >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val) >>> nn.train(output_val, 1000, False) >>> nn.predict([0, 1, 0]) in (0, 1) True """ # Input values for which the predictions are to be made. self.array = input_arr self.layer_between_input_and_first_hidden_layer = sigmoid( np.dot(self.array, self.input_layer_and_first_hidden_layer_weights) ) self.layer_between_first_hidden_layer_and_second_hidden_layer = sigmoid( np.dot( self.layer_between_input_and_first_hidden_layer, self.first_hidden_layer_and_second_hidden_layer_weights, ) ) self.layer_between_second_hidden_layer_and_output = sigmoid( np.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer, self.second_hidden_layer_and_output_layer_weights, ) ) return int((self.layer_between_second_hidden_layer_and_output > 0.6)[0]) def sigmoid(value: np.ndarray) -> np.ndarray: """ Applies sigmoid activation function. return normalized values >>> sigmoid(np.array(([1, 0, 2], [1, 0, 0]), dtype=np.float64)) array([[0.73105858, 0.5 , 0.88079708], [0.73105858, 0.5 , 0.5 ]]) """ return 1 / (1 + np.exp(-value)) def sigmoid_derivative(value: np.ndarray) -> np.ndarray: """ Provides the derivative value of the sigmoid function. returns derivative of the sigmoid value >>> sigmoid_derivative(np.array(([1, 0, 2], [1, 0, 0]), dtype=np.float64)) array([[ 0., 0., -2.], [ 0., 0., 0.]]) """ return (value) * (1 - (value)) def example() -> int: """ Example for "how to use the neural network class and use the respected methods for the desired output". Calls the TwoHiddenLayerNeuralNetwork class and provides the fixed input output values to the model. Model is trained for a fixed amount of iterations then the predict method is called. In this example the output is divided into 2 classes i.e. binary classification, the two classes are represented by '0' and '1'. >>> example() in (0, 1) True """ # Input values. test_input = np.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ), dtype=np.float64, ) # True output values for the given input values. output = np.array(([0], [1], [1], [0], [1], [0], [0], [1]), dtype=np.float64) # Calling neural network class. neural_network = TwoHiddenLayerNeuralNetwork( input_array=test_input, output_array=output ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. neural_network.train(output=output, iterations=10, give_loss=False) return neural_network.predict(np.array(([1, 1, 1]), dtype=np.float64)) if __name__ == "__main__": example()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/neural_network/activation_functions/squareplus.py
neural_network/activation_functions/squareplus.py
""" Squareplus Activation Function Use Case: Squareplus designed to enhance positive values and suppress negative values. For more detailed information, you can refer to the following link: https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Squareplus """ import numpy as np def squareplus(vector: np.ndarray, beta: float) -> np.ndarray: """ Implements the SquarePlus activation function. Parameters: vector (np.ndarray): The input array for the SquarePlus activation. beta (float): size of the curved region Returns: np.ndarray: The input array after applying the SquarePlus activation. Formula: f(x) = ( x + sqrt(x^2 + b) ) / 2 Examples: >>> squareplus(np.array([2.3, 0.6, -2, -3.8]), beta=2) array([2.5 , 1.06811457, 0.22474487, 0.12731349]) >>> squareplus(np.array([-9.2, -0.3, 0.45, -4.56]), beta=3) array([0.0808119 , 0.72891979, 1.11977651, 0.15893419]) """ return (vector + np.sqrt(vector**2 + beta)) / 2 if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/neural_network/activation_functions/binary_step.py
neural_network/activation_functions/binary_step.py
""" This script demonstrates the implementation of the Binary Step function. It's an activation function in which the neuron is activated if the input is positive or 0, else it is deactivated It's a simple activation function which is mentioned in this wikipedia article: https://en.wikipedia.org/wiki/Activation_function """ import numpy as np def binary_step(vector: np.ndarray) -> np.ndarray: """ Implements the binary step function Parameters: vector (ndarray): A vector that consists of numeric values Returns: vector (ndarray): Input vector after applying binary step function >>> vector = np.array([-1.2, 0, 2, 1.45, -3.7, 0.3]) >>> binary_step(vector) array([0, 1, 1, 1, 0, 1]) """ return np.where(vector >= 0, 1, 0) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/neural_network/activation_functions/softplus.py
neural_network/activation_functions/softplus.py
""" Softplus Activation Function Use Case: The Softplus function is a smooth approximation of the ReLU function. For more detailed information, you can refer to the following link: https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Softplus """ import numpy as np def softplus(vector: np.ndarray) -> np.ndarray: """ Implements the Softplus activation function. Parameters: vector (np.ndarray): The input array for the Softplus activation. Returns: np.ndarray: The input array after applying the Softplus activation. Formula: f(x) = ln(1 + e^x) Examples: >>> softplus(np.array([2.3, 0.6, -2, -3.8])) array([2.39554546, 1.03748795, 0.12692801, 0.02212422]) >>> softplus(np.array([-9.2, -0.3, 0.45, -4.56])) array([1.01034298e-04, 5.54355244e-01, 9.43248946e-01, 1.04077103e-02]) """ return np.log(1 + np.exp(vector)) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/neural_network/activation_functions/scaled_exponential_linear_unit.py
neural_network/activation_functions/scaled_exponential_linear_unit.py
""" Implements the Scaled Exponential Linear Unit or SELU function. The function takes a vector of K real numbers and two real numbers alpha(default = 1.6732) & lambda (default = 1.0507) as input and then applies the SELU function to each element of the vector. SELU is a self-normalizing activation function. It is a variant of the ELU. The main advantage of SELU is that we can be sure that the output will always be standardized due to its self-normalizing behavior. That means there is no need to include Batch-Normalization layers. References : https://iq.opengenus.org/scaled-exponential-linear-unit/ """ import numpy as np def scaled_exponential_linear_unit( vector: np.ndarray, alpha: float = 1.6732, lambda_: float = 1.0507 ) -> np.ndarray: """ Applies the Scaled Exponential Linear Unit function to each element of the vector. Parameters : vector : np.ndarray alpha : float (default = 1.6732) lambda_ : float (default = 1.0507) Returns : np.ndarray Formula : f(x) = lambda_ * x if x > 0 lambda_ * alpha * (e**x - 1) if x <= 0 Examples : >>> scaled_exponential_linear_unit(vector=np.array([1.3, 3.7, 2.4])) array([1.36591, 3.88759, 2.52168]) >>> scaled_exponential_linear_unit(vector=np.array([1.3, 4.7, 8.2])) array([1.36591, 4.93829, 8.61574]) """ return lambda_ * np.where(vector > 0, vector, alpha * (np.exp(vector) - 1)) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/neural_network/activation_functions/soboleva_modified_hyperbolic_tangent.py
neural_network/activation_functions/soboleva_modified_hyperbolic_tangent.py
""" This script implements the Soboleva Modified Hyperbolic Tangent function. The function applies the Soboleva Modified Hyperbolic Tangent function to each element of the vector. More details about the activation function can be found on: https://en.wikipedia.org/wiki/Soboleva_modified_hyperbolic_tangent """ import numpy as np def soboleva_modified_hyperbolic_tangent( vector: np.ndarray, a_value: float, b_value: float, c_value: float, d_value: float ) -> np.ndarray: """ Implements the Soboleva Modified Hyperbolic Tangent function Parameters: vector (ndarray): A vector that consists of numeric values a_value (float): parameter a of the equation b_value (float): parameter b of the equation c_value (float): parameter c of the equation d_value (float): parameter d of the equation Returns: vector (ndarray): Input array after applying SMHT function >>> vector = np.array([5.4, -2.4, 6.3, -5.23, 3.27, 0.56]) >>> soboleva_modified_hyperbolic_tangent(vector, 0.2, 0.4, 0.6, 0.8) array([ 0.11075085, -0.28236685, 0.07861169, -0.1180085 , 0.22999056, 0.1566043 ]) """ # Separate the numerator and denominator for simplicity # Calculate the numerator and denominator element-wise numerator = np.exp(a_value * vector) - np.exp(-b_value * vector) denominator = np.exp(c_value * vector) + np.exp(-d_value * vector) # Calculate and return the final result element-wise return numerator / denominator if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/neural_network/activation_functions/mish.py
neural_network/activation_functions/mish.py
""" Mish Activation Function Use Case: Improved version of the ReLU activation function used in Computer Vision. For more detailed information, you can refer to the following link: https://en.wikipedia.org/wiki/Rectifier_(neural_networks)#Mish """ import numpy as np from .softplus import softplus def mish(vector: np.ndarray) -> np.ndarray: """ Implements the Mish activation function. Parameters: vector (np.ndarray): The input array for Mish activation. Returns: np.ndarray: The input array after applying the Mish activation. Formula: f(x) = x * tanh(softplus(x)) = x * tanh(ln(1 + e^x)) Examples: >>> mish(vector=np.array([2.3,0.6,-2,-3.8])) array([ 2.26211893, 0.46613649, -0.25250148, -0.08405831]) >>> mish(np.array([-9.2, -0.3, 0.45, -4.56])) array([-0.00092952, -0.15113318, 0.33152014, -0.04745745]) """ return vector * np.tanh(softplus(vector)) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/neural_network/activation_functions/gaussian_error_linear_unit.py
neural_network/activation_functions/gaussian_error_linear_unit.py
""" This script demonstrates an implementation of the Gaussian Error Linear Unit function. * https://en.wikipedia.org/wiki/Activation_function#Comparison_of_activation_functions The function takes a vector of K real numbers as input and returns x * sigmoid(1.702*x). Gaussian Error Linear Unit (GELU) is a high-performing neural network activation function. This script is inspired by a corresponding research paper. * https://arxiv.org/abs/1606.08415 """ import numpy as np def sigmoid(vector: np.ndarray) -> np.ndarray: """ Mathematical function sigmoid takes a vector x of K real numbers as input and returns 1/ (1 + e^-x). https://en.wikipedia.org/wiki/Sigmoid_function >>> sigmoid(np.array([-1.0, 1.0, 2.0])) array([0.26894142, 0.73105858, 0.88079708]) """ return 1 / (1 + np.exp(-vector)) def gaussian_error_linear_unit(vector: np.ndarray) -> np.ndarray: """ Implements the Gaussian Error Linear Unit (GELU) function Parameters: vector (np.ndarray): A numpy array of shape (1, n) consisting of real values Returns: gelu_vec (np.ndarray): The input numpy array, after applying gelu Examples: >>> gaussian_error_linear_unit(np.array([-1.0, 1.0, 2.0])) array([-0.15420423, 0.84579577, 1.93565862]) >>> gaussian_error_linear_unit(np.array([-3])) array([-0.01807131]) """ return vector * sigmoid(1.702 * vector) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false