|
3 | 3 | Reference: https://math.stackexchange.com/questions/3973429/what-is-a-logarithmic-series
|
4 | 4 | """
|
5 | 5 |
|
| 6 | + |
6 | 7 | def logarithmic_series(x: float, n_terms: int = 5, expand: bool = False) -> list:
|
7 | 8 | """
|
8 | 9 | Returns the logarithmic series for a number x (log x) upto n terms.
|
9 |
| - |
| 10 | +
|
10 | 11 | Parameters:
|
11 | 12 | x: a floating point number for log(x)
|
12 | 13 | n_terms: number of terms to be computed
|
13 | 14 | expand: Set this flag to get the terms as real numbers, unset for unsolved expressions
|
14 |
| - |
| 15 | +
|
15 | 16 | Examples:
|
16 | 17 | >>> logarithmic_series(3)
|
17 | 18 | ['(2^1)/1', '-(2^2)/2', '(2^3)/3', '-(2^4)/4', '(2^5)/5']
|
18 |
| - |
| 19 | +
|
19 | 20 | >>> logarithmic_series(-3)
|
20 | 21 | ['-(4^1)/1', '(4^2)/2', '-(4^3)/3', '(4^4)/4', '-(4^5)/5']
|
21 |
| - |
| 22 | +
|
22 | 23 | >>> logarithmic_series(3, 10)
|
23 | 24 | ['(2^1)/1', '-(2^2)/2', '(2^3)/3', '-(2^4)/4', '(2^5)/5', '-(2^6)/6', '(2^7)/7', '-(2^8)/8', '(2^9)/9', '-(2^10)/10']
|
24 |
| - |
| 25 | +
|
25 | 26 | >>> logarithmic_series(3, expand=True)
|
26 | 27 | [2.0, -2.0, 2.6666666666666665, -4.0, 6.4]
|
27 | 28 | """
|
28 |
| - n_times_x_minus_1: float = x-1 |
| 29 | + n_times_x_minus_1: float = x - 1 |
29 | 30 | n: int = 1
|
30 | 31 | series: list = []
|
31 | 32 | for _ in range(n_terms):
|
32 |
| - if (expand): |
33 |
| - series.append(((-1)**(n+1))*(n_times_x_minus_1/n)) |
34 |
| - n_times_x_minus_1 *= (x-1) |
| 33 | + if expand: |
| 34 | + series.append(((-1) ** (n + 1)) * (n_times_x_minus_1 / n)) |
| 35 | + n_times_x_minus_1 *= x - 1 |
35 | 36 | else:
|
36 |
| - sign: str = '-' if (-1)**(n+1) == -1 else '' |
37 |
| - term: str = sign+'('+str(x-1)+'^'+str(n)+')'+'/'+str(n) |
38 |
| - if (term.startswith("-(-")): |
39 |
| - term = '('+term[3::] |
40 |
| - elif (term.startswith("(-")): |
41 |
| - term = "-("+term[2::] |
| 37 | + sign: str = "-" if (-1) ** (n + 1) == -1 else "" |
| 38 | + term: str = sign + "(" + str(x - 1) + "^" + str(n) + ")" + "/" + str(n) |
| 39 | + if term.startswith("-(-"): |
| 40 | + term = "(" + term[3::] |
| 41 | + elif term.startswith("(-"): |
| 42 | + term = "-(" + term[2::] |
42 | 43 | series.append(term)
|
43 | 44 | n += 1
|
44 | 45 | return series
|
45 | 46 |
|
46 |
| -if (__name__ == "__main__"): |
| 47 | + |
| 48 | +if __name__ == "__main__": |
47 | 49 | import doctest
|
| 50 | + |
48 | 51 | doctest.testmod()
|
0 commit comments