Skip to content
Closed
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions maths/series/logarithmic_series.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""
This is an implementation of logarithmic series in Python.
Reference: https://math.stackexchange.com/questions/3973429/what-is-a-logarithmic-series
"""

def logarithmic_series(x: float, n_terms: int = 5, expand: bool = False) -> list:
"""
Returns the logarithmic series for a number x (log x) upto n terms.

Check failure on line 9 in maths/series/logarithmic_series.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

maths/series/logarithmic_series.py:9:1: W293 Blank line contains whitespace
Parameters:
x: a floating point number for log(x)
n_terms: number of terms to be computed
expand: Set this flag to get the terms as real numbers,
unset for unsolved expressions

Check failure on line 15 in maths/series/logarithmic_series.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

maths/series/logarithmic_series.py:15:1: W293 Blank line contains whitespace
Examples:
>>> logarithmic_series(3)
['(2^1)/1', '-(2^2)/2', '(2^3)/3', '-(2^4)/4', '(2^5)/5']

Check failure on line 19 in maths/series/logarithmic_series.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

maths/series/logarithmic_series.py:19:1: W293 Blank line contains whitespace
>>> logarithmic_series(-3)
['-(4^1)/1', '(4^2)/2', '-(4^3)/3', '(4^4)/4', '-(4^5)/5']

Check failure on line 22 in maths/series/logarithmic_series.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

maths/series/logarithmic_series.py:22:1: W293 Blank line contains whitespace
>>> logarithmic_series(3, 6)
['(2^1)/1', '-(2^2)/2', '(2^3)/3', '-(2^4)/4', '(2^5)/5', '-(2^6)/6']

Check failure on line 25 in maths/series/logarithmic_series.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

maths/series/logarithmic_series.py:25:1: W293 Blank line contains whitespace
>>> logarithmic_series(3, expand=True)
[2.0, -2.0, 2.6666666666666665, -4.0, 6.4]
"""
n_times_x_minus_1: float = x-1
n: int = 1
series: list = []
for _ in range(n_terms):
if (expand):
series.append(((-1)**(n+1))*(n_times_x_minus_1/n))
n_times_x_minus_1 *= (x-1)
else:
sign: str = '-' if (-1)**(n+1) == -1 else ''
term: str = sign+'('+str(x-1)+'^'+str(n)+')'+'/'+str(n)
if (term.startswith("-(-")):
term = '('+term[3::]
elif (term.startswith("(-")):
term = "-("+term[2::]
series.append(term)
n += 1
return series

if (__name__ == "__main__"):
import doctest
doctest.testmod()
Loading