โโโโโโโโโโโโโ
A forever work in progress library full of mathematical equations, constants, and algorithms.
- Algorithms
- Constants
- Functions
- Sequences
- Hyperbolic Functions
- Complex Number
- Real Number
- Rational Number
- Integral Number
This is a Python class that implements various algorithms, including finding the greatest common divisor using Euclid's algorithm, computing logarithms with a specified base, counting the occurrences of words in a text, and performing operations with fractions.
Returns the sum of integers and/or floats.
- *args [int | float]:
A variable-length argument list of integers and/or floats
- [int | float]:
The sum of the integers and/or floats in *args
Returns integers or float of given numbers after being subtracted.
- *args ([int | float]):
A variable-length argument list of integers and/or floats
- [int | float]:
The result of subtracting the integers and/or floats in *args from the first argument
Returns an integer or float of given numbers multiplied.
- *args ([int | float]):
A variable-length argument list of integers and/or floats
- [int | float]:
The product of the integers and/or floats in *args
Returns a float of dividend divided by divisor.
- dividend ([int | float]):
The number to be divided (dividend)
- divisor ([int | float]):
The number to divide by (divisor)
- [int | float]:
The result of dividing the dividend by the divisor, as a float
Returns an integer of dividend divided by divisor.
- dividend ([int | float]):
The number to be divided (dividend)
- divisor ([int | float]):
The number to divide by (divisor)
- [int | float]:
The result of dividing the dividend by the divisor, rounded down to the nearest integer
Returns the remainder of dividend divided by divisor.
- dividend ([int | float]):
The number to be divided (dividend)
- divisor ([int | float]):
The number to divide by (divisor)
- [int | float]:
The remainder of dividing the dividend by the divisor
Returns base to the power of exponent.
- base ([int | float]):
The base of the power operation
- exponent ([int | float]):
The exponent of the power operation
- [int | float]:
The result of raising the base to the power of the exponent
Returns the logarithm of x with a specified base (default is 10)
- x (int/float):
The value for which to compute the logarithm
- base (int/float, optional):
The base of the logarithm. Defaults to 10.
- [int | float]:
The logarithm of x with the specified base
Returns the natural logarithm of x (base e)
- x (int/float):
The value for which to compute the natural logarithm
The natural logarithm of x
Returns the logarithm of x (base 10)
- x (int/float):
The value for which to compute the logarithm
The logarithm of x (base 10)
Returns the sum of multiple fractions
- *args (tuples):
Multiple fractions represented as tuples of the form (numerator, denominator)
A tuple representing the sum of all fractions in reduced form (numerator, denominator)
Finds the greatest common divisor of two numbers using Euclid's algorithm.
- a:
An integer
- b:
Another integer
The greatest common divisor of a and b
Returns a dictionary containing the count of each word in the given text.
- text (str):
The text to count the words in.
A dictionary where the keys are the unique words in the text and the values are the count of each word.
Returns the product of multiple fractions.
- An arbitrary number of arguments. Each argument must be a tuple with two values, the numerator and denominator of a fraction.
A tuple containing the numerator and denominator of the product of the fractions.
- ValueError:
If any of the arguments are not tuples of length 2 or if any of the denominators are 0.
Returns the result of dividing one fraction by another.
- Two tuples, each with two values, representing the numerator and denominator of the two fractions.
A tuple containing the numerator and denominator of the quotient of the two fractions.
- ValueError:
If any of the arguments are not tuples of length 2.
- ZeroDivisionError:
If the denominator of the second fraction is zero.
Returns the fourth proportional number given three proportional numbers.
- a (int):
The first proportional number.
- b (int):
The second proportional number.
- c (int, optional):
The third proportional number. Defaults to None.
- d (int, optional):
The fourth proportional number. Defaults to None.
- int:
The fourth proportional number calculated from the input.
If both `c` and `d` are None, `a` and `b` are assumed to be the first two proportional numbers, and `c` and `d` are set to `b` and `a` respectively. If `d` is None, `a` and `b` are assumed to be the first two proportional numbers, and `d` is calculated from `c` using the formula `d = (b * c) / a`. If `c` and `d` are both specified, `a` and `b` are assumed to be the first two proportional numbers, and the function calculates the fourth proportional number `x` using the formula `x = (b * d) / c`.
This function converts a percantage x
to a fraction.
- x (float):
percentage
The fraction form of a percentage
This function converts a fraction given by numerator
and denominator
to a percentage.
- numerator:
The numerator of the fraction.
- denominator:
The denominator of the fraction.
The fraction as a percentage.
Searches for the target element in the given list and returns the index if found, otherwise returns -1.
- lst : list
The list to be searched.
- target : any
The target element to be searched for in the list.
- int
If the target is found in the list, the index of the target is returned.
Otherwise, -1 is returned.
Searches for the target element in the given list using binary search and returns the index if found, otherwise returns -1.
- lst : list
The list to be searched.
- target : any
The target element to be searched for in the list.
- int
If the target is found in the list, the index of the target is returned.
Otherwise, -1 is returned.
Sorts the given list in ascending order using bubble sort and returns the sorted list.
- lst (list):
The list to be sorted.
- list:
The sorted list in ascending order.
Sorts the given list in ascending order using insertion sort and returns the sorted list.
- lst (list):
The list to be sorted.
- list:
The sorted list in ascending order.
Sorts the given list in ascending order using merge sort and returns the sorted list.
- lst (list):
The list to be sorted.
- list:
The sorted list in ascending order.
This function computes the square root of a given number num
using the Babylonian method.
- num (float):
The number to find the square root of.
- float:
The square root of the given number.
This function computes the factorial of a given number num
.
- num (int):
The number to find the factorial of.
- int:
The factorial of the given number.
Compute the nth number in the Fibonacci sequence.
- n (int):
The index of the desired Fibonacci number.
- int:
The nth number in the Fibonacci sequence.
Check whether a given number is prime.
- num (int):
The number to check for primality.
- bool:
True if the number is prime, False otherwise.
Compute the greatest common divisor of two or more numbers.
- *args (int):
Two or more numbers to find the GCD of.
- int:
The greatest common divisor of the given numbers.
Compute the least common multiple of two or more numbers.
- *args (int):
Two or more numbers to find the LCM of.
- int:
The least common multiple of the given numbers.
This function takes a list of numbers and returns a sorted list in ascending or descending order.
- numbers (List[[int | float]]):
A list of integers or floats to be sorted.
- reverse (bool, optional):
If True, returns the list in descending order. Defaults to False.
- List[[int | float]]:
A sorted list in ascending or descending order.
This function takes a sorted list of numbers and a target number and returns the index of the target number, or -1 if it is not found.
- numbers (List[[int | float]]):
A sorted list of integers or floats.
- target ([int | float]):
The number to search for in the list.
- int:
The index of the target number in the list, or -1 if it is not found.
Calculates the equation of the line of best fit (y = mx + b) for the given x and y values.
- x (list):
A list of x values.
- y (list):
A list of corresponding y values.
- tuple:
A tuple containing the slope (m) and y-intercept (b) of the line of best fit.
This function takes in two matrices A and B of the same size, and returns their sum.
- A:
A list of lists of floats representing the first matrix.
- B:
list of lists of floats representing the second matrix.
A list of lists of floats representing the sum of the matrices.
This function multiplies two matrices A and B and returns the resulting matrix.
- A:
The first matrix.
- B:
The second matrix.
A list of lists of floats representing the product of matrices A and B.
This function inverts a matrix A and returns the resulting matrix.
- A:
The matrix to be inverted.
A list of lists of floats representing the inverted matrix of A.
Multiplies two matrices A and B and returns the resulting matrix.
- A (list[list[float]]):
The first matrix.
- B (list[list[float]]):
The second matrix.
- list[list[float]]:
The matrix product of A and B.
Inverts a matrix A and returns the resulting matrix.
- A (list[list[float]]):
The matrix to be inverted.
- list[list[float]]:
The inverted matrix of A.
Use Newton's method to find the root of a function f.
- f (function):
The function for which to find the root.
- f_prime (function):
The derivative of f.
- x0 (float):
The initial guess for the root.
- epsilon (float):
The desired level of accuracy.
- root (float):
The estimated root of the function.
Use gradient descent to find the minimum of a function f.
- f (function):
The function to minimize.
- f_prime (function):
The derivative of f.
- x0 (float):
The initial guess for the minimum.
- alpha (float):
The step size.
- max_iters (int):
The maximum number of iterations.
- minimum (float):
The estimated minimum of the function.
Use Monte Carlo simulation to estimate the probability of an event.
- n (int):
The number of simulations to run.
- f (function):
A function that returns True or False for a given sample.
- probability (float):
The estimated probability of the event.
Calculates the Euclidean distance between two points in a two-dimensional space.
- point1 (tuple):
A tuple containing the coordinates of the first point as (x, y).
- point2 (tuple):
A tuple containing the coordinates of the second point as (x, y).
- float:
The Euclidean distance between point1 and point2.
The distance between the two points
A simple pseudorandom number generator based on the linear congruential method.
- seed (int):
The seed value used to initialize the generator.
- A float between 0 and 1.
Use k-means clustering to group data points into k clusters.
- data (list):
A list of data points.
- k (int):
The number of clusters to form.
- clusters (list): A list of k clusters, each containing the data points assigned to that cluster.
Returns the exponential value of a number.
- num:
a number whose exponential value is to be calculated
The exponential value of the input number
Returns the absolute value of a number.
- num:
a number whose absolute value is to be calculated
The absolute value of the input number
Returns the remainder of dividing the dividend by the divisor.
- dividend:
the number to be divided
- divisor:
the number to divide by
The remainder of dividing the dividend by the divisor
Returns the sine value of a number.
- num:
a number in radians whose sine value is to be calculated
The sine value of the input number
Returns the cosine value of a number.
- num:
a number in radians whose cosine value is to be calculated
The cosine value of the input number
Returns the tangent value of a number.
- num:
a number in radians whose tangent value is to be calculated
The tangent value of the input number
Finds the smallest prime number greater than n.
- n (int):
A positive integer.
- int:
The smallest prime number greater than n.
Return the arc tangent of x, in radians.
- x (float):
The value whose arc tangent is to be returned.
- float
The arc tangent of x, in radians.
Helper function for atan. Computes the arc tangent of x in the interval [0, 1].
- x (float):
The value whose arc tangent is to be returned.
- float
The arc tangent of x, in radians.
Calculates the arctangent of x using a Taylor series approximation.
- x (float):
A real number.
- float:
The arctangent of x in radians.
Returns a list of prime numbers up to n using the sieve of Eratosthenes algorithm.
- n (int):
the upper limit of the list.
- List[int]:
a list of prime numbers up to n.
Returns the value of the Riemann zeta function.
- s (float):
The argument of the zeta function.
- zeta_1 (complex):
The initial value of the Riemann zeta function.
- n (int):
The number of iterations to perform.
- complex:
The value of the Riemann zeta function.
Compute the histogram of a list of data with a specified number of bins.
- data (list):
A list of numeric data
- num_bins (int):
The number of bins to use in the histogram
- tuple:
A tuple containing the counts for each bin and the edges of the bins
Returns an iterator that produces a slice of elements from the given iterable.
- iterable (iterable):
The iterable to slice.
- start (int):
The index at which to start the slice.
- stop (int):
The index at which to stop the slice.
- step (int, optional):
The step size between slice elements. Defaults to 1.
- iterator:
An iterator that produces the slice of elements.
Calculates the cumulative distribution function (CDF) of a standard normal distribution at a given value.
- x (float):
The value at which to calculate the CDF.
- float:
The CDF of the standard normal distribution at x, accurate to 10 decimal places.
This is a Python class full of mathematical constants such a Pi or the speed of light.
Returns the speed of light in meters per second
- None
The speed of light in meters/second at 299_792_458
Returns the Planck constant, denoted as h, in joule-seconds.
The Planck constant is a physical constant that is fundamental to quantum mechanics. It relates the energy of a photon to its frequency and is approximately 6.626 x 10^-34 J*s.
- float:
The value of the Planck constant in joule-seconds.
The ratio of a circle's circumference to its diameter.
- None
- Pi ฯ:
to the 20th decimal
3.141_592_653_589_793_238_46
the 19th letter of the Greek alphabet, representing the voiceless dental or alveolar plosive IPA: [t]. In the system of Greek numerals, it has a value of 300.
- None
- tau, uppercase ฮค, lowercase ฯ, or ฯ:
to the 20th decimal
6.283_185_307_179_586_476_92
"The Golden Ratio" In mathematics, two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities.
- None
- Uppercase ฮฆ lowercase ฯ or ฯ:
Value to the 20th decimal
1.618_033_988_749_894_848_20
"The Silver Ratio". Two quantities are in the silver ratio (or silver mean) if the ratio of the smaller of those two quantities to the larger quantity is the same as the ratio of the larger quantity to the sum of the smaller quantity and twice the larger quantity
- None
- ฮดS:
Value to the 20th decimal
2.414_213_562_373_095_048_80
Returns the mathematical constant psi (the supergolden ratio).
- None
- ฯ:
to the 25th decimal
return 1.465_571_231_876_768_026_656_731_2
Returns the connective constant for the hexagonal lattice.
- None
- ฮผ:
to the 4th decimal
1.687_5
In plane geometry, the KeplerโBouwkamp constant (or polygon inscribing constant) is obtained as a limit of the following sequence. Take a circle of radius 1. Inscribe a regular triangle in this circle. Inscribe a circle in this triangle. Inscribe a square in it. Inscribe a circle, regular pentagon, circle, regular hexagon and so forth.
- None
- K':
to the 20th decimal
0.114_942_044_853_296_200_70
Returns Wallis's constant.
- None
Value to the 20th decimal
2.094_551_481_542_326_591_48
A mathematical constant approximately equal to 2.71828 that can be characterized in many ways. It is the base of the natural logarithms. It is the limit of (1 + 1/n)n as n approaches infinity, an expression that arises in the study of compound interest. It can also be calculated as the sum of the infinite series
- None
- e:
Value to the 20th decimal. math.e
2.718_281_828_459_045_235_36
Natural logarithm of 2.
- None
- ln 2:
Value to the 30th decimal. math.log(2)
0.693_147_180_559_945_309_417_232_121_458
The ratio of the perimeter of Bernoulli's lemniscate to its diameter, analogous to the definition of ฯ for the circle.
- None
- ฯ:
Value to the 20th decimal. math.sqrt(2)
2.622_057_554_292_119_810_46
Not to be confused with Euler's Number. Defined as the limiting difference between the harmonic series and the natural logarithm
- None
- ฮณ:
Value to the 50th decimal
0.577_215_664_901_532_860_606_512_090_082_402_431_042_159_335_939_92
The sum of the reciprocals of the Mersenne numbers
- None
- E:
Value to the 20th decimal. sum([1 / 2 ** (2 ** i) for i in range(40)])
1.606_695_152_415_291_763_78
Defined as the unique real number that satisfies the equation ฮฉe**ฮฉ = 1.
- None
- ฮฉ:
Value to the 30th decimal
0.567_143_290_409_783_872_999_968_662_210
The sum of the reciprocals of the positive cubes.
- None
- ฮถ(3):
Value to the 45th decimal
1.202_056_903_159_594_285_399_738_161_511_449_990_764_986_292
The maximum value of the eccentricity for which a solution to Kepler's equation, in terms of a power series in the eccentricity, converges.
- None
Value to the 35th decimal
0.662_743_419_349_181_580_974_742_097_109_252_90
A mathematical constant defined as the unique positive zero of the logarithmic integral function.
- None
- ฮผ โ:
Value to the 45th decimal
1.451_369_234_883_381_050_283_968_485_892_027_449_493_032_28
Transcendental mathematical constant that is the ratio of the perimeter of Bernoulli's lemniscate to its diameter, analogous to the definition of ฯ for the circle.
- None
- G == ฯ /ฯ โ 0.8346268:
Value to the 7th decimal
0.834_626_8
summary
- None
- ฮณ2 :
Value to the 20th decimal
1.154_700_538_379_251_529_01
A real number x with the property that, for every positive integer n, there exists a pair of integers (p,q) with q>1.
- None
- L:
Value to the 119th decimal
0.110_001_000_000_000_000_000_001_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000_01
summary
- None
- C_{1}:
_description_
0.697_774_657_964_007_982_01
The transcendental number, which is an almost integer, in that it is very close to an integer.
- None
- e**{{\pi {\sqrt {163}}}}:
Value to the 18th decimal
262_537_412_640_768_743.999_999_999_999_250_073
A mathematical constant, related to the K-function and the Barnes G-function.
- None
- A:
Value to the 20th decimal
1.282_427_129_100_622_636_87
Computes the Catalan's constant to the specified number of decimal places using the formula:
- n (int):
The number of terms to sum to approximate the constant.
- float:
The computed value of the Catalan's constant.
>>> catalan_constant(1000000)
0.915965594177219
Calculates the unique real root of the equation cos(x) = x, known as the Dottie number, to the 20th decimal place.
The Dottie number is a constant that arises in the study of iterative methods and has connections to chaos theory.
- None
- float:
The Dottie number, i.e., the unique real root of the equation cos(x) = x, to the 20th decimal place.
>>> dottie_number()
0.73908513321516064165
Returns the Meissel-Mertens constant M to the 40th decimal place.
The Meissel-Mertens constant M is defined as the sum of the reciprocal of the primes up to n, where n is an arbitrary positive integer. It has important connections to prime number theory and the Riemann hypothesis.
This function uses a precomputed value of M to return the constant to the 40th decimal place.
- None
- M (float):
The Meissel-Mertens constant M to the 40th decimal place.
return 0.261_497_212_847_642_783_755_426_838_608_695_859_051_6
meissel_mertens_constant()
0.2614972128476427837554268386086958590516
The ratio, for any parabola, of the arc length of the parabolic segment formed by the latus rectum to the focal parameter.
- None
- P:
Value to the 20th decimal
2.295_587_149_392_638_074_03
The value of an infinite series of unit fractions with alternating signs.
- None
- C:
Value to the 20th decimal
0.643_410_546_288_338_026_18
Calculates Gelfond's Constant, which is defined as e raised to the power of pi.
- none
- float:
The value of Gelfond's Constant, which is approximately 23.1406926327792690057292.
return self.eulers_constant**self.pi
Returns the Gelfond-Schneider constant, which is a transcendental number defined as the value of 2^(1/2) raised to the power of itself, or approximately 2.6651441426902251886502972498731.
- none
- float:
The value of the Gelfond-Schneider constant.
pass
Returns the Second Favard constant, which is a mathematical constant defined as the limit of the arithmetic mean of the reciprocal of consecutive odd numbers, or approximately 0.661707182...
- none
- float:
The value of the Second Favard constant.
pass
Returns the golden angle constant, which is the angle subtended by the smaller of the two angles formed by dividing the circumference of a circle in the golden ratio. It is equal to (3 - sqrt(5)) * 180 degrees / pi, or approximately 137.5077640500378546463487 degrees.
- none
- float:
The value of the golden angle constant in degrees.
pass
Returns Sierpiลski's constant, which is the fractal dimension of the Sierpiลski triangle, a self-similar fractal shape. It is equal to log(3)/log(2), or approximately 1.585.
- none
- float:
The value of Sierpiลski's constant.
pass
Returns the Landau-Ramanujan constant, which is a mathematical constant that appears in the asymptotic expansion of the partition function. It is equal to e^(pi * sqrt(163)), or approximately 2.2932021438344677e+17.
- none
- float:
The value of the Landau-Ramanujan constant.
pass
Returns the First Nielsen-Ramanujan constant, which is a mathematical constant that appears in certain partition identities. It is equal to the product of a series involving the gamma function, or approximately 0.866081804933.
- none
- float:
The value of the First Nielsen-Ramanujan constant.
pass
Returns Gieseking's constant, which is a mathematical constant that appears in the theory of harmonic analysis. It is equal to (2*pi)^(-3/4), or approximately 0.7511255444649425.
- none
- float:
The value of Gieseking's constant.
pass
Returns Bernstein's constant, which is a mathematical constant that appears in the theory of Fourier analysis. It is equal to pi/sqrt(2), or approximately 2.221441469079183.
- none
- float:
The value of Bernstein's constant.
pass
Returns the Tribonacci constant, which is a mathematical constant defined as the unique real root of the polynomial x^3 - x^2 - x - 1, or approximately 1.8392867552141612.
- none
float:
The value of the Tribonacci constant.
pass
Returns the limiting value of the sequence a(n) = sum(k=1 to n) 1/prime(k), where prime(k) is the kth prime number.
- none
- float:
The value of Bruns constant, accurate to 42 decimal places.
pass
Returns the limiting value of the sequence of twin primes (pairs of prime numbers that differ by 2).
- none
- float:
The value of the twin primes constant, accurate to 36 decimal places.
pass
Returns the unique positive real root of x^3 = x + 1.
- none
- float:
The value of the plastic number, accurate to 32 decimal places.
pass
Returns the limiting value of the sequence of numbers that represent the Bloch wall widths in ferromagnets.
- none
- float:
The value of Bloch's constant, accurate to 34 decimal places.
pass
Returns the value that has 97.5% of the area under a standard normal distribution to the left of it.
- none
- float:
The value of the z-score at the 97.5th percentile, accurate to 9 decimal places.
pass
Returns the limiting value of the sequence of numbers that represent the probability that a random permutation of n elements will have no cycle of length greater than log(n).
- none
- float:
The value of Landau's constant, accurate to 19 decimal places.
pass
Returns the limiting value of the sequence of numbers that represent the probability that a random permutation of n elements will have no cycle of length greater than sqrt(n) * log(n).
- none
- float:
The value of Landau's third constant, accurate to 20 decimal places.
pass
Returns the limiting value of the sequence of numbers that represent the differences in density between the 0's and 1's in the Prouhet-Thue-Morse sequence.
- none
- float:
The value of the Prouhet-Thue-Morse constant, accurate to 20 decimal places.
pass
The Golomb-Dickman constant represents the limiting distribution of the ratio of the k-th smallest number in a sample of n random numbers to n^(1/k) as n approaches infinity. It is denoted by G.
- none
- float:
The value of the Golomb-Dickman constant G, approximately 0.6243299885435508.
return 0.6243299885435508
The Lebesgue asymptotic behavior constant describes the average size of the level sets of a random walk in d dimensions. It is denoted by L(d).
- none
- float:
The value of the Lebesgue asymptotic behavior constant L(3), approximately 3.912023005428146.
return 3.912023005428146
The Feller-Tornier constant is the probability that a random walk on the integers returns to the origin infinitely often. It is denoted by F.
- none
- float:
The value of the Feller-Tornier constant F, approximately 0.259183.
return 0.259183
The Champernowne constant is formed by concatenating the base 10 representations of successive integers, and is represented by C_10.
- none
- float:
The value of the base 10 Champernowne constant C_10, approximately 0.12345678910111213...
The Salem number is a complex number that is a root of a certain polynomial with integer coefficients. It is denoted by s.
- none
- complex:
The value of the Salem constant s, approximately (1+sqrt(2)) * e^(pi*sqrt(2)/4).
return (1 + 2 ** 0.5) * Algorithm.exp(Constants.pi * 2 ** 0.5 / 4)
The Khinchin constant is a number that appears in the theory of continued fractions. It is denoted by K.
- none
- float:
The value of the Khinchin constant K, approximately 2.6854520010653065.
return 2.6854520010653065
Levy's constant, also known as the LevyโKhinchin constant, is a mathematical constant that arises in the study of Levy processes, which are stochastic processes that exhibit properties such as long-range dependence and heavy tails. It is defined as the limit of the average absolute difference between two random variables divided by their root-mean-square difference, as the sample size tends to infinity. The value of Levy's constant is approximately 1.3303872425, with high precision being 1.33038724246235217434246.
- ฮณ or K
- none
- float:
The value of Levy's constant.
return 1.330_387_242_462_352_174_342_46
Calculate the value of e to the power of Levy's constant.
- none
- float:
The value of e to the power of Levy's constant.
return Algorithm.exp(self.levys_constant)
Copeland-Erdลs constant is the smallest number that is not the sum of distinct non-negative integer powers of 2.
- C_E
- none
- float
Gompertz constant is a mathematical constant named after Benjamin Gompertz, it is the limit of the ratio between the life expectancy of a certain age and the remaining life expectancy.
- ฮณ
- none
- float
De BruijnโNewman constant is the limit of the sequence of coefficients a_n such that the entire function f(z) = ฮ _(n=1)^โ [(1 - z/a_n) * exp(z/a_n)] has no zeros in the complex plane.
- ฮป
- none
- float
The van der Pauw constant is a constant used in measuring resistance of flat samples, and is defined as the ratio of the natural logarithm of the quotient of two measured resistances to the constant ฯ.
- K
- none
- float:
The value of the van der Pauw constant to the highest precision.
return Algorithm.exp(Constants.pi * MathFunctions.copysign(1, MathFunctions.acos(1/Constants.pi)))
Magic angle is an angle of rotation for the bilayer graphene where the electronic properties of the material exhibit a number of interesting phenomena.
- ฮธ
- none
- float:
The magic angle in radians.
return Constants.arctan(Algorithm.square_root(3))
Calculates the arctangent of x using a Taylor series approximation.
- x (float): A real number.
- float:
The arctangent of x in radians.
The Artin's constant is a number that appears in the formula to calculate the Artin-Mazur zeta function. It is defined as the infinite product of (1 - p^(-s)) where p ranges over all prime numbers and s is the reciprocal of the prime number.
- none
- float:
The value of the Artin's constant to the highest precision.
Porter's constant is a mathematical constant that appears in the field of information theory. It is defined as the limit of the ratio of the maximum number of different words of length n over the number of possible words of length n as n approaches infinity.
-
- none
- float:
The value of Porter's constant to the highest precision.
return Algorithm.exp**(1/Constants.euler_mascheroni_constant)
Returns the Euler-Mascheroni constant, a mathematical constant that appears in many areas of mathematics. It is defined as the limit of the difference between the harmonic series and the natural logarithm of n as n approaches infinity.
The function calculates the value of the Euler-Mascheroni constant using a sum of the harmonic series and the natural logarithm of n. The sum is taken over a large number of terms to achieve a high degree of accuracy.
Note that the function uses the 'math' module to calculate the natural logarithm, so it must be imported before the function can be called.
- none
- float:
The value of the Euler-Mascheroni constant to a high degree of accuracy.
Lochs' constant is a mathematical constant defined as the limiting ratio of the perimeter of an inscribed regular decagon to its diameter.
-
- none
- float:
The value of Lochs' constant to the highest precision.
return Algorithm.square_root(2 + Algorithm.square_root(2 + Algorithm.square_root(2 + Algorithm.square_root(2 + Algorithm.square_root(2)))))
The De Vries - De Vos - Barendrecht - De Klerk - Smit - Smit constant (also known as De Vries' tesseract constant) is defined as the number that describes the maximum ratio of the content of a hypercube inscribed in a tesseract to the content of the hypercube circumscribed about the tesseract.
-
- none
- float:
The value of De Vries' tesseract constant to the highest precision.
return Algorithm.square_root(2 + Algorithm.square_root(2)) / (2 * Algorithm.square_root(2))
The Lieb's square ice constant is the infinite sum of alternating sign reciprocals of the squares of odd positive integers. It appears in the square ice problem in statistical mechanics.
-
- none
- float:
The value of the Lieb's square ice constant to the highest precision.
return Constants.pi / (Algorithm.square_root(3) * Algorithm.log((3 + Algorithm.square_root(8)) / 2))
Niven's constant is a mathematical constant that is the only known integer x that is divisible by the sum of its digits when written in decimal base. The constant is also related to the convergence of certain infinite series.
-
- none
- int:
The value of Niven's constant to the highest precision.
Mills constant is the smallest positive real number A such that the floor function of the double exponential function is a prime number, where the double exponential function is f(n) = A^(3^n).
- A
- none
- float
Stephens' constant is a mathematical constant that arises in the study of prime numbers.
- float:
The value of Stephens' constant.
return 0.5364798721
The regular paperfolding sequence is a binary sequence that arises in the study of fractal geometry.
- str:
The regular paperfolding sequence as a string of 0s and 1s.
return "110110011100100"
The reciprocal Fibonacci constant is a real number that arises in the study of Fibonacci numbers.
- float:
The value of the reciprocal Fibonacci constant.
return 1.1319882488
ChvรกtalโSankoff constant for the binary alphabet.
- \gamma_{2}
- float:
The value of the ChvรกtalโSankoff constant.
return 1.7550327129
Feigenbaum constant ฮด
- \delta
- float:
The value of the Feigenbaum constant.
return 4.6692016091
Chaitin's constant is a real number that encodes the halting probability of a universal Turing machine.
- \Omega
- ValueError:
If the computation of the constant fails.
- float:
The value of Chaitin's constant.
Robbins' constant is a mathematical constant that arises in the study of mathematical analysis.
- \Delta (3)
- ValueError:
If the computation of the constant fails.
- none
- float:
The value of Robbins' constant.
Weierstrass' constant is a mathematical constant that arises in the study of elliptic functions.
- float:
The value of Weierstrass' constant.
return 0.5174790617
Returns Fransen-Robinson constant which is the smallest positive root of the following polynomial equation:
x^3 - x^2 - 1 = 0
- F
- ValueError:
If the root cannot be found
- float:
The Fransen-Robinson constant
Returns Feigenbaum constant alpha which relates to the period-doubling bifurcation in chaotic systems.
- \alpha
- ValueError:
If the constant cannot be computed
- float:
The Feigenbaum constant alpha
Returns the Second du Bois-Reymond constant, which is defined as the supremum of the absolute values of the Fourier coefficients of a bounded variation function with period 1.
- C_{2}
- ValueError:
If the constant cannot be computed
- float:
The Second du Bois-Reymond constant
Returns the ErdลsโTenenbaumโFord constant which is related to the distribution of prime numbers.
- \delta
- ValueError:
If the constant cannot be computed
- float:
The ErdลsโTenenbaumโFord constant
Returns Conway's constant, which is the unique real root of the following polynomial equation:
x^3 - x - 1 = 0
- \lambda
- Self (object): The class instance
- ValueError:
If the root cannot be found
- float:
Conway's constant
Returns Backhouse's constant which is defined as the smallest k such that the inequality n! > k^n holds for all positive integers n.
- B
- ValueError:
If the constant cannot be computed
- float:
Backhouse's constant
Returns Viswanath's constant, which is the limiting distribution of the ratios of successive gaps in the sequence of zeros of the Riemann zeta function.
- \Omega_V
- ValueError:
If the constant cannot be computed
- float:
Viswanath's constant
Returns Komornik-Loreti constant, which is the unique positive real root of the following polynomial equation:
x^2 - x - 1 = 0
- q
- ValueError:
If the root cannot be found
- float:
Komornik-Loreti constant
Computes the Embree-Trefethen constant, which is defined as the supremum of the real parts of the poles of a certain rational function.
- {\displaystyle \beta ^{\star }}
- ValueError:
If the computation fails to converge.
- float:
The computed value of the Embree-Trefethen constant.
- * Embree, M., & Trefethen, L. N. (1999). Growth and decay of random plane waves.
- Communications on Pure and Applied Mathematics, 52(7), 757-788.
- * Trefethen, L. N. (2006). Spectral methods in MATLAB. SIAM.
Computes the Heath-Brown-Moroz constant, which is defined as the product of the Euler-Mascheroni constant and the reciprocal of a certain infinite product.
- C
- ValueError:
If the computation fails to converge.
- float:
The computed value of the Heath-Brown-Moroz constant.
- * Heath-Brown, D. R. (1984). The fourth power moment of the Riemann zeta-function.
- Proceedings of the London Mathematical Society, 49(2), 475-513.
- * Moroz, B. Z. (2001). Some constants associated with the Riemann zeta function.
- Journal of Mathematical Analysis and Applications, 261(1), 235-251.
Computes the MRB constant, which is defined as the sum of the alternating series obtained by raising the first n positive integers to their own powers and then summing them with alternating signs.
- S
- ValueError:
If the computation fails to converge.
- float:
The computed value of the MRB constant.
- * Borwein, J. M., Bradley, D. M., & Crandall, R. E. (1999). Computational strategies for
- the Riemann zeta function. Journal of Computational and Applied Mathematics, 121(1-2), 247-296.
- * Bradley, D. M. (2004). Multiple q-zeta values. Ramanujan Journal, 8(1), 39-65.
Computes the Prime constant, which is defined as the product of the reciprocals of the primes minus ln(ln(2)).
- \rho
- ValueError:
If the computation fails to converge.
- float:
The computed value of the Prime constant.
- * Meissel, L. (1879). Bestimmung einer zahl, welche zu der logaritmierten primzahlfunction
- ฯ(x) in nรคherung den nรคmlichen wert wie die zahl x selbst gibt.
- Journal fรผr die Reine und Angewandte Mathematik, 1879(88), 127-133.
- * Lehmer, D. H. (1959). List of computed values of the prime-counting function ฯ(x)
- from x= 10^6 to x= 10^20. U. S. National Bureau of Standards Applied Mathematics Series, 46.
Returns the Somos quadratic recurrence constant.
- \sigma
- ValueError:
If the calculation is not valid.
- float:
The value of the Somos quadratic recurrence constant.
Returns the Foias constant.
- \alpha
- ValueError:
If the calculation is not valid.
- float:
The value of the Foias constant.
Returns the logarithmic capacity of the unit disk.
- ValueError:
If the calculation is not valid.
- float:
The value of the logarithmic capacity.
return 2
Returns the Taniguchi constant.
- ValueError:
If the calculation is not valid.
- float:
The value of the Taniguchi constant.
A class containing various mathematical functions.
Compute the value of the gamma function at the given value of x.
- Args:
x (float): The value at which the gamma function is to be evaluated.
- float:
The value of the gamma function at the given value of x.
- ValueError:
If x is negative and not an integer.
- The gamma function is defined as the integral from zero to infinity of t^(x-1) * exp(-t) dt.
- For positive integers, the gamma function can be computed recursively as (n-1)!.
- For x <= 0, the gamma function is undefined, but we return NaN to avoid raising an error.
Calculates the area of a circle given its radius.
- r:
The radius of the circle.
- float:
The area of the circle.
return 3.141592653589793238 * r ** 2
Calculates the volume of a sphere given its radius.
- r:
The radius of the sphere.
- float:
The volume of the sphere.
return 4 / 3 * 3.141592653589793238 * r ** 3
Calculates the perimeter of a rectangle given its length and breadth.
- l:
The length of the rectangle.
- b:
The breadth of the rectangle.
- float:
The perimeter of the rectangle.
return 2 * (l + b)
Calculates the length of the hypotenuse of a right-angled triangle given the lengths of its two other sides.
- a:
The length of one of the sides of the triangle.
- b:
The length of the other side of the triangle.
The length of the hypotenuse of the triangle.
return (a ** 2 + b ** 2) ** 0.5
Calculates the square root of a given number.
- x:
The number to take the square root of.
The square root of x.
return x ** 0.5
Calculates the factorial of a given number.
- n:
The number to calculate the factorial of.
- int:
The factorial of n.
fact = 1
for i in range(1, n+1):
fact *= i
return fact
Calculates the greatest common divisor of two numbers.
- a:
The first number.
- b:
The second number.
- int:
The greatest common divisor of a and b.
while(b):
a, b = b, a % b
return a
Calculates the least common multiple of two numbers.
- a:
The first number.
- b:
The second number.
- int:
The least common multiple of a and b.
return a * b // self.gcd(a, b)
Calculates the value of e raised to a given power.
- x:
The exponent.
- float:
The value of e raised to x.
e = 2.718281828459045235
return e ** x
Calculates the logarithm of a given number to a given base.
- x:
The number to take the logarithm of.
- base:
The base of the logarithm.
The logarithm of x to the base.
return (Functions.log(x) / Functions.log(base))
Calculates the natural logarithm of a given number.
x: The number to take the natural logarithm of.
The natural logarithm of x.
if x <= 0:
return float('nan')
elif x == 1:
return 0.0
else:
return Functions.integrate(1/x, 1, x)
Approximates the definite integral of a function over a given interval using the trapezoidal rule.
- f:
The function to integrate.
- a:
The lower limit of the interval.
- b:
The upper limit of the interval.
The approximate value of the definite integral of f over the interval [a, b].
n = 1000 # Number of trapezoids to use
dx = (b - a) / n
x_values = [a + i * dx for i in range(n+1)]
y_values = [f(x) for x in x_values]
return (dx/2) * (y_values[0] + y_values[-1] + 2*sum(y_values[1:-1]))
Calculates the surface area of a cylinder given its radius and height.
- r:
The radius of the cylinder.
- h:
The height of the cylinder.
The surface area of the cylinder.
return 2 * 3.14159265358979323846 * r * (r + h)
Calculates the volume of a cylinder given its radius and height.
- r:
The radius of the cylinder.
- h:
The height of the cylinder.
- float:
The volume of the cylinder.
return 3.14159265358979323846 * r ** 2 * h
Calculates the area of a triangle given its base and height.
- b:
The base of the triangle.
- h:
The height of the triangle.
- float:
The area of the triangle.
return 0.5 * b * h
Calculates the sine of a given angle in radians.
- x: The angle in radians.
- float:
The sine of the angle.
x = x % (2 * 3.141592653589793238)
sign = 1 if x > 0 else -1
x *= sign
if x > 3.141592653589793238:
x -= 2 * 3.141592653589793238
sign *= -1
return sign * (
x - x ** 3 / 6 + x ** 5 / 120 - x ** 7 / 5040 + x ** 9 / 362880
)
Return a float with the magnitude of x and the sign of y.
- x (float):
The magnitude of the result.
- y (float):
The sign of the result.
- float
A float with the magnitude of x and the sign of y.
Return the arc cosine of x, in radians.
- x (float):
The value whose arc cosine is to be returned.
- float
The arc cosine of x, in radians.
Approximates the definite integral of a function using the adaptive quadrature method.
func (callable): A function to integrate.
a (float): Lower limit of integration.
b (float): Upper limit of integration.
eps (float): Desired accuracy.
maxiter (int): Maximum number of iterations.
float: The definite integral of the function over the interval [a, b].
adaptivesimpson(a, b, eps, fa, fb, fc, level):
c = (a + b) / 2
h = b - a
d = (a + c) / 2
e = (c + b) / 2
fd = func(d)
fe = func(e)
Sleft = h * (fa + 4 * fd + fc) / 6
Sright = h * (fc + 4 * fe + fb) / 6
S2 = Sleft + Sright
if level >= maxiter or abs(S2 - Sleft - Sright) <= 15 * eps:
return S2 + (S2 - Sleft - Sright) / 15
return adaptivesimpson(a, c, eps / 2, fa, fc, fd, level + 1) + adaptivesimpson(c, b, eps / 2, fc, fb, fe, level + 1)
fa = func(a)
fb = func(b)
fc = func((a + b) / 2)
return adaptivesimpson(a, b, eps, fa, fb, fc, 0)
Generates all possible non-empty subsets of a given iterable.
s (iterable): The iterable for which subsets are generated.
generator: A generator that yields each subset as a tuple.
s = list(s)
n = len(s)
for i in range(1, 2**n):
subset = tuple(s[j] for j in range(n) if (i >> j) & 1)
yield subset
Approximates the limit of a function f(x) as x approaches x0.
func (function): A function of one variable.
x0 (float): The value of x that x approaches.
h (float, optional): Step size for computing the numerical derivative. Defaults to 1e-8.
max_iterations (int, optional): Maximum number of iterations for the numerical approximation. Defaults to 1000.
tol (float, optional): Tolerance level for stopping iterations. Defaults to 1e-8.
float: The numerical approximation of the limit.
f = func
x = x0
for i in range(max_iterations):
f_x = f(x)
f_x_plus_h = f(x + h)
derivative = (f_x_plus_h - f_x) / h
x -= f_x / derivative
if abs(f(x)) < tol:
return f(x)
raise ValueError(f"Failed to converge to a limit within {max_iterations} iterations.")
Returns the greatest integer less than or equal to x.
x (float): A floating-point number.
int: The greatest integer less than or equal to x.
return int(x) if x >= 0 else int(x) - 1
Find a root of a function in the interval [a, b] using Brent's method.
f (callable): The function to find the root of.
a (float): The left endpoint of the interval.
b (float): The right endpoint of the interval.
maxiter (int, optional): The maximum number of iterations to perform. Defaults to 100.
float: The root of the function.
ValueError: If the root cannot be found within the maximum number of iterations.
The nth harmonic number is the sum of the reciprocals of the first n natural numbers.
- H_n
- n (int):
The number of terms to include in the sum.
- float:
The value of the nth harmonic number.
return sum(1/i for i in range(1, n+1))
The nth Gregory coefficient is a coefficient used in the Gregory series formula for pi, which provides an approximate value of pi.
- G_n
- n (int):
The index of the Gregory coefficient to be calculated.
- float:
The value of the nth Gregory coefficient.
if n == 0:
return 1
elif n % 2 == 0:
return 0
else:
return -2 / (n * Constants.pi) * self.gregory_coefficients(n-1)
The nth Bernoulli number is a sequence of rational numbers with deep connections to number theory and other areas of mathematics, including algebra and calculus.
- B_n
- n (int):
The index of the Bernoulli number to be calculated.
- float:
The value of the nth Bernoulli number.
if n == 0:
return 1
elif n == 1:
return -0.5
else:
sum_term = sum(MathFunctions.combination(n+1, k) * self.bernoulli_number(k) / (n+1-k) for k in range(1, n))
return 1 - sum_term
The nth Hermite constant is a constant that appears in the study of the quantum harmonic oscillator, and is related to the normalization of the wave functions of the oscillator.
- H_n
- n (int):
The index of the Hermite constant to be calculated.
- float:
The value of the nth Hermite constant.
if n == 0:
return 1
else:
return (-1)**n * Algorithm.factorial(n-1)
The nth Hafner-Sarnak-McCurley constant is a constant that appears in the study of prime numbers and related topics in number theory.
- C_n
- n (int):
The index of the Hafner-Sarnak-McCurley constant to be calculated.
- float:
The value of the nth Hafner-Sarnak-McCurley constant.
return sum(Algorithm.exp(-n/p)/p for p in Algorithm.sieve_of_eratosthenes(2*n+1))
Returns the nth Stieltjes constant.
- n (int):
the index of the sequence.
- float:
the nth Stieltjes constant.
if n == 1:
return 0.57721566490153286060651209 # gamma
elif n == 2:
return 1.20205690315959428539973816 # G
elif n == 3:
return 1.79175946922805500081247735 # pi^2/6
elif n == 4:
return 2.9456101084887218059356 # 7*G - 4*pi^2/3
elif n == 5:
return 4.4428829381583661417149 # 3*zeta(3) - 2*G
else:
raise ValueError("The index n should be between 1 and 5.")
- https://mathworld.wolfram.com/StieltjesConstants.html
Returns the nth Favard constant.
- n (int):
the index of the sequence.
- float:
the nth Favard constant.
if n < 1:
raise ValueError("The index n should be a positive integer.")
elif n == 1:
return 1
else:
return sum([Sequences.favard_constants(self, i) * Sequences.favard_constants(self, n-i) / (i+n-i-1)
for i in range(1, n)])
- https://mathworld.wolfram.com/FavardConstants.html
Returns the nth generalized Bruns constant.
- n (int):
the index of the sequence.
- float:
the nth generalized Bruns constant.
if n < 1:
raise ValueError("The index n should be a positive integer.")
elif n == 1:
return 1
else:
return sum([abs(Sequences.generalized_bruns_constant(self, i) - Sequences.generalized_bruns_constant(self, i-1))
for i in range(2, n+1)]) + 1
- https://mathworld.wolfram.com/GeneralizedBrunsConstant.html
Returns the nth Champernowne constant.
- n (int):
the index of the sequence.
- float:
the nth Champernowne constant.
if n < 1:
raise ValueError("n should be a positive integer")
if n == 1:
return 0.12345678910111213141516171819202122
else:
prev = self.champernowne_constants(n-1)
return float(str(prev) + str(n+8))
- https://mathworld.wolfram.com/ChampernowneConstant.html
Returns the nth Lagrange number.
- n (int):
the index of the sequence.
- int:
the nth Lagrange number.
if n < 1:
raise ValueError("n should be a positive integer")
if n == 1:
return 1
else:
return n * self.lagrange_number(n-1) - (-1)**n
- https://mathworld.wolfram.com/LagrangeNumber.html
Returns the nth Feller's coin-tossing constant.
- n (int):
the index of the sequence.
- float:
the nth Feller's coin-tossing constant.
result = 0
for k in range(n + 1):
result += (-1) ** k / (2 ** (2 ** k))
return result
- https://mathworld.wolfram.com/FellersCoin-TossingConstants.html
Returns the nth Stoneham number.
- n (int):
the index of the sequence.
- int:
the nth Stoneham number.
if n == 0:
return 1
else:
return (3 * Sequences.stoneham_number(n - 1) + 1) // 2
- https://mathworld.wolfram.com/StonehamNumber.html
Returns the nth Beraha constant.
- n (int):
the index of the sequence.
- float:
the nth Beraha constant.
if n == 0:
return 1
else:
return 1 + 1 / Sequences.beraha_constants(n - 1)
- https://mathworld.wolfram.com/BerahasConstant.html
Returns the nth Chvรกtal-Sankoff constant.
- n (int):
the index of the sequence.
- float:
the nth Chvรกtal-Sankoff constant.
result = 0
for k in range(n + 1):
binom = MathFunctions.comb(2 ** k, k)
result += (-1) ** k * binom ** 2
return result
- https://mathworld.wolfram.com/Chvatal-SankoffConstants.html
Computes the hyperharmonic number H(n,p), which is defined as the sum of the p-th powers of the reciprocals of the first n positive integers.
- n - (int):
The positive integer up to which to compute the sum.
- p (int):
The exponent to which to raise the reciprocals of the integers.
- H -
(float): The hyperharmonic number H(n,p).
H = 0
for i in range(1, n+1):
H += 1 / i ** p
return H
- H(n,p):
hyperharmonic number of order p and degree n.
Computes the nth Gregory number, which is defined as the alternating sum of the reciprocals of the odd positive integers, up to the nth term.
- n - (int):
The positive integer up to which to compute the alternating sum.
- G - (float):
The nth Gregory number.
G = 0
for i in range(1, n+1):
if i % 2 == 1:
G += 1 / i
else:
G -= 1 / i
return G
- G(n):
nth Gregory number.
Computes the value of the metallic mean of x, which is the positive solution to the equation x = 1/(1+x).
- x(float):
The value for which to compute the metallic mean.
- mm
(float): The value of the metallic mean of x.
mm = (1 + Algorithm.square_root(1 + 4*x)) / 2
return mm
- mm(x):
metallic mean of x.
A class representing the six hyperbolic functions: sinh, cosh, tanh, coth, sech, and csch.
- * Weisstein, E. W. (n.d.). Hyperbolic functions. MathWorld--A Wolfram Web Resource.
- Retrieved October 11, 2021, from https://mathworld.wolfram.com/HyperbolicFunctions.html
Returns the hyperbolic sine of x.
- x (float):
The input value in radians.
- float:
The hyperbolic sine of x.
return (Algorithm.exp(x) - Algorithm.exp(-x)) / 2
Returns the hyperbolic cosine of x.
- x (float):
The input value in radians.
- float:
The hyperbolic cosine of x.
return (Algorithm.exp(x) + Algorithm.exp(-x)) / 2
Returns the hyperbolic tangent of x.
- x (float):
The input value in radians.
- float:
The hyperbolic tangent of x.
return HyperbolicFunctions.sinh(x) / HyperbolicFunctions.cosh(x)
Returns the hyperbolic cotangent of x.
- x (float):
The input value in radians.
- float:
The hyperbolic cotangent of x.
return 1 / HyperbolicFunctions.tanh(x)
Returns the hyperbolic secant of x.
- x (float):
The input value in radians.
- float:
The hyperbolic secant of x.
return 1 / HyperbolicFunctions.cosh(x)
Returns the hyperbolic cosecant of x.
- x(float):
The input value in radians.
- float:
The hyperbolic cosecant of x.
return 1 / HyperbolicFunctions.sinh(x)
A class representing a complex number.
- real (float): The real part of the complex number.
- imag (float): The imaginary part of the complex number.
Initializes a complex number.
- real (float): The real part of the complex number.
- imag (float): The imaginary part of the complex number.
Returns a string representation of the complex number.
- str:
A string representation of the complex number.
return f"{self.real} + {self.imag}j"
Adds two complex numbers.
- other (ComplexNumber): The complex number to add.
- ComplexNumber: The sum of the two complex numbers.
return ComplexNumber(self.real + other.real, self.imag + other.imag)
Subtracts two complex numbers.
- other (ComplexNumber): The complex number to subtract.
- ComplexNumber: The difference of the two complex numbers.
return ComplexNumber(self.real - other.real, self.imag - other.imag)
Multiplies two complex numbers.
- other (ComplexNumber): The complex number to multiply.
- ComplexNumber: The product of the two complex numbers.
real = self.real * other.real - self.imag * other.imag
imag = self.real * other.imag + self.imag * other.real
return ComplexNumber(real, imag)
Divides two complex numbers.
- other (ComplexNumber): The complex number to divide.
- ComplexNumber: The quotient of the two complex numbers.
denom = other.real**2 + other.imag**2
real = (self.real * other.real + self.imag * other.imag) / denom
imag = (self.imag * other.real - self.real * other.imag) / denom
return ComplexNumber(real, imag)
Computes the conjugate of the complex number.
- ComplexNumber: The conjugate of the complex number.
return ComplexNumber(self.real, -self.imag)
Computes the modulus (magnitude) of the complex number.
- float:
The modulus of the complex number.
return (self.real**2 + self.imag**2)**0.5
A class representing a real number.
Initializes a new RealNumber object with the given value.
- value (float):
The value of the real number.
- RealNumber:
A new RealNumber object.
self.value = value
Returns a string representation of the real number.
- str:
A string representation of the real number.
return str(self.value)
Returns a string representation of the real number.
- str:
A string representation of the real number.
return str(self.value)
Checks whether the real number is equal to another object.
- other (object):
The object to compare with.
- bool:
True if the real number is equal to the other object, False otherwise.
if isinstance(other, RealNumber):
return self.value == other.value
elif isinstance(other, float):
return self.value == other
else:
return False
Checks whether the real number is not equal to another object.
- other (object):
The object to compare with.
- bool:
True if the real number is not equal to the other object, False otherwise.
return not self.__eq__(other)
Checks whether the real number is less than another object.
- other (object):
The object to compare with.
- bool:
True if the real number is less than the other object, False otherwise.
if isinstance(other, RealNumber):
return self.value < other.value
elif isinstance(other, float):
return self.value < other
else:
return NotImplemented
Checks whether the real number is less than or equal to another object.
- other (object):
The object to compare with.
- bool:
True if the real number is less than or equal to the other object, False otherwise.
if isinstance(other, RealNumber):
return self.value <= other.value
elif isinstance(other, float):
return self.value <= other
else:
return NotImplemented
Checks whether the real number is greater than another object.
- other (object):
The object to compare with.
- bool:
True if the real number is greater than the other object, False otherwise.
if isinstance(other, RealNumber):
return self.value > other.value
elif isinstance(other, float):
return self.value > other
else:
return NotImplemented
Checks whether the real number is greater than or equal to another object.
- other (object):
The object to compare with.
- bool:
True if the real number is greater than or equal to the other object, False otherwise.
if isinstance(other, RealNumber):
return self.value >= other.value
elif isinstance(other, float):
return self.value >= other
else:
return NotImplemented
Adds two RealNumber objects.
- other (RealNumber or float):
The RealNumber object or float to add.
- RealNumber:
A new RealNumber object with the sum of the two numbers.
if isinstance(other, RealNumber):
return RealNumber(self.value + other.value)
elif isinstance(other, float):
return RealNumber(self.value + other)
else:
return NotImplemented
Subtracts two RealNumber objects.
- other (RealNumber or float):
The RealNumber object or float to subtract.
- RealNumber:
A new RealNumber object with the difference of the two numbers.
if isinstance(other, RealNumber):
return RealNumber(self.value - other.value)
elif isinstance(other, float):
return RealNumber(self.value - other)
else:
return NotImplemented
Multiplies two RealNumber objects.
- other (RealNumber or float):
The RealNumber object or float to multiply.
- RealNumber:
A new RealNumber object with the product of the two numbers.
if isinstance(other, RealNumber):
return RealNumber(self.value * other.value)
elif isinstance(other, float):
return RealNumber(self.value * other)
else:
return NotImplemented
Divides two RealNumber objects.
- other (RealNumber or float):
The RealNumber object or float to divide by.
- RealNumber:
A new RealNumber object with the quotient of the two numbers.
if isinstance(other, RealNumber):
return RealNumber(self.value / other.value)
elif isinstance(other, float):
return RealNumber(self.value / other)
else:
return NotImplemented
Returns the absolute value of the RealNumber object.
- RealNumber:
A new RealNumber object with the absolute value of the number.
return RealNumber(abs(self.value))
Returns the negation of the RealNumber object.
- RealNumber:
A new RealNumber object with the negation of the number.
return RealNumber(-self.value)
Returns the square root of the RealNumber object.
- RealNumber:
A new RealNumber object with the square root of the number.
return RealNumber(self.value ** 0.5)
Computes the power of the real number to the given exponent.
- other (float):
The exponent.
- RealNumber:
A new RealNumber object with the result of the power operation.
return RealNumber(self.value ** other)
A class representing a rational number.
- numerator (int):
The numerator of the rational number.
- denominator (int):
The denominator of the rational number.
- simplify:
Simplifies the rational number.
- add:
Adds two rational numbers.
- subtract:
Subtracts two rational numbers.
- multiply:
Multiplies two rational numbers.
- divide:
Divides two rational numbers.
Initializes a rational number with the given numerator and denominator.
- numerator (int):
The numerator of the rational number.
- denominator (int):
The denominator of the rational number.
- ValueError:
If the denominator is zero.
if denominator == 0:
raise ValueError("Denominator cannot be zero")
self.numerator = numerator
self.denominator = denominator
self.simplify()
Returns the string representation of the rational number.
return f"{self.numerator}/{self.denominator}"
Simplifies the rational number.
gcd = self.gcd(self.numerator, self.denominator)
self.numerator //= gcd
self.denominator //= gcd
Computes the greatest common divisor of two numbers a and b.
- a (int): The first number.
- b (int): The second number.
- int:
The greatest common divisor of a and b.
while b:
a, b = b, a % b
return a
Adds two rational numbers.
- other (RationalNumber): The other rational number.
- RationalNumber: The sum of the two rational numbers.
numerator = self.numerator * other.denominator + other.numerator * self.denominator
denominator = self.denominator * other.denominator
return RationalNumber(numerator, denominator)
Subtracts two rational numbers.
- other (RationalNumber): The other rational number.
- RationalNumber: The difference of the two rational numbers.
numerator = self.numerator * other.denominator - other.numerator * self.denominator
denominator = self.denominator * other.denominator
return RationalNumber(numerator, denominator)
Multiplies two rational numbers.
- other (RationalNumber): The other rational number.
- RationalNumber: The product of the two rational numbers.
numerator = self.numerator * other.numerator
denominator = self.denominator * other.denominator
return RationalNumber(numerator, denominator)
Divides two rational numbers.
- other (RationalNumber): The other rational number.
- RationalNumber: The quotient of the two rational numbers.
numerator = self.numerator * other.denominator
denominator = self.denominator * other.numerator
return RationalNumber(numerator, denominator)
A class representing integral numbers.
- value: int
The value of the integral number.
__init__(self, value: int) -> None:
Initializes a new instance of the IntegralNumber class with the specified integer value.
__repr__(self) -> str:
Returns a string representation of the IntegralNumber object.
__eq__(self, other: 'IntegralNumber') -> bool:
Determines if the current IntegralNumber object is equal to another IntegralNumber object.
__lt__(self, other: 'IntegralNumber') -> bool:
Determines if the current IntegralNumber object is less than another IntegralNumber object.
__add__(self, other: 'IntegralNumber') -> 'IntegralNumber':
Adds two IntegralNumber objects and returns a new IntegralNumber object.
__sub__(self, other: 'IntegralNumber') -> 'IntegralNumber':
Subtracts two IntegralNumber objects and returns a new IntegralNumber object.
__mul__(self, other: 'IntegralNumber') -> 'IntegralNumber':
Multiplies two IntegralNumber objects and returns a new IntegralNumber object.
__truediv__(self, other: 'IntegralNumber') ->
'IntegralNumber':
Divides two IntegralNumber objects and returns a new IntegralNumber object.
- TypeError:
If the argument is not an instance of IntegralNumber.
- ZeroDivisionError:
If the second IntegralNumber object is zero and division is attempted.
Divides two IntegralNumber objects and returns a new IntegralNumber object.
- https://en.wikipedia.org/wiki/Integer_(computer_science)
- https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types
Initializes a new instance of the IntegralNumber class with the specified integer value.
- value: int
The integer value to initialize the IntegralNumber object with.
self.value = value
Returns a string representation of the IntegralNumber object.
- str:
A string representation of the IntegralNumber object.
return f"IntegralNumber({self.value})"
Determines if the current IntegralNumber object is equal to another IntegralNumber object.
- other : IntegralNumber
The IntegralNumber object to compare to.
- bool:
True if the objects are equal, False otherwise.
if isinstance(other, IntegralNumber):
return self.value == other.value
return False
Determines if the current IntegralNumber object is less than another IntegralNumber object.
- other : IntegralNumber
The IntegralNumber object to compare to.
- bool:
True if the current object is less than the other object, False otherwise.
if isinstance(other, IntegralNumber):
return self.value < other.value
return False
Adds two IntegralNumber objects.
- other : IntegralNumber
The IntegralNumber object to be added to the current object.
- IntegralNumber
An IntegralNumber object which is the sum of the current object and the passed object.
- TypeError
If the passed object is not an IntegralNumber.
if isinstance(other, IntegralNumber):
return IntegralNumber(self.value + other.value)
raise TypeError("Cannot add non-IntegralNumber object.")
Subtracts two IntegralNumber objects.
- other : IntegralNumber
The IntegralNumber object to be subtracted from the current object.
- IntegralNumber
An IntegralNumber object which is the difference between the current object and the passed object.
- TypeError
If the passed object is not an IntegralNumber.
if isinstance(other, IntegralNumber):
return IntegralNumber(self.value - other.value)
raise TypeError("Cannot subtract non-IntegralNumber object.")
Multiplies two IntegralNumber objects.
- other : IntegralNumber
The IntegralNumber object to be multiplied with the current object.
- IntegralNumber
An IntegralNumber object which is the product of the current object and the passed object.
- TypeError
If the passed object is not an IntegralNumber.
if isinstance(other, IntegralNumber):
return IntegralNumber(self.value * other.value)
raise TypeError("Cannot multiply non-IntegralNumber object.")
Divides two IntegralNumber objects.
- other : IntegralNumber
The IntegralNumber object to be used as divisor for the current object.
- TypeError
If the passed object is not an IntegralNumber.
- ZeroDivisionError
If the passed object has a value of zero.
- IntegralNumber
An IntegralNumber object which is the result of dividing the current object by the passed object.
if isinstance(other, IntegralNumber):
if other.value == 0:
raise ZeroDivisionError("Cannot divide by zero.")
return IntegralNumber(self.value // other.value)
raise TypeError("Cannot divide non-IntegralNumber object.")
Returns the sum of this number and other
.
- other : IntegralNumber
The number to add to this number.
- IntegralNumber
The sum of this number and `other`.
return IntegralNumber(self.value + other.value)
Returns the difference between this number and other
.
- other : IntegralNumber
The number to subtract from this number.
- IntegralNumber
The difference between this number and `other`.
return IntegralNumber(self.value - other.value)
Returns the product of this number and other
.
- other : IntegralNumber
The number to multiply with this number.
- IntegralNumber
The product of this number and `other`.
return IntegralNumber(self.value * other.value)
Returns the quotient of this number and other
.
- other : IntegralNumber
The number to divide this number by.
- [IntegralNumber | None]
The quotient of this number and `other`. Returns None if `other` is zero.
if other.value == 0:
return None
return IntegralNumber(self.value // other.value)
- str(self.value)