Coverage for gpkit/tools/tools.py: 100%

30 statements

, created at 2022-07-28 12:36 -0400

1"""Non-application-specific convenience methods for GPkit"""

2import numpy as np

5def te_exp_minus1(posy, nterm):

6 """Taylor expansion of e^{posy} - 1

8 Arguments

9 ---------

10 posy : gpkit.Posynomial

11 Variable or expression to exponentiate

12 nterm : int

13 Number of non-constant terms in resulting Taylor expansion

15 Returns

16 -------

17 gpkit.Posynomial

18 Taylor expansion of e^{posy} - 1, carried to nterm terms

19 """

20 res = 0

21 factorial_denom = 1

22 for i in range(1, nterm + 1):

23 factorial_denom *= i

24 res += posy**i / factorial_denom

25 return res

28def te_secant(var, nterm):

29 """Taylor expansion of secant(var).

31 Arguments

32 ---------

33 var : gpkit.monomial

34 Variable or expression argument

35 nterm : int

36 Number of non-constant terms in resulting Taylor expansion

38 Returns

39 -------

40 gpkit.Posynomial

41 Taylor expansion of secant(x), carried to nterm terms

42 """

43 # The first 12 Euler Numbers

44 E2n = np.asarray([1.0,

45 5,

46 61,

47 1385,

48 50521,

49 2702765,

50 199360981,

51 19391512145,

52 2404879675441,

53 370371188237525,

54 69348874393137901,

55 15514534163557086905])

56 if nterm > 12:

57 n_extend = np.asarray(range(13, nterm+1))

58 E2n_add = (8 * np.sqrt(n_extend/np.pi)

59 * (4*n_extend/(np.pi * np.exp(1)))**(2*n_extend))

62 res = 1

63 factorial_denom = 1

64 for i in range(1, nterm + 1):

65 factorial_denom *= ((2*i)*(2*i-1))

66 res = res + var**(2*i) * E2n[i-1] / factorial_denom

67 return res

70def te_tangent(var, nterm):

71 """Taylor expansion of tangent(var).

73 Arguments

74 ---------

75 var : gpkit.monomial

76 Variable or expression argument

77 nterm : int

78 Number of non-constant terms in resulting Taylor expansion

80 Returns

81 -------

82 gpkit.Posynomial

83 Taylor expansion of tangent(x), carried to nterm terms

84 """

85 if nterm > 15:

86 raise NotImplementedError("Tangent expansion not implemented above"

87 " 15 terms")

89 # The first 15 Bernoulli Numbers

90 B2n = np.asarray([1/6,

91 -1/30,

92 1/42,

93 -1/30,

94 5/66,

95 -691/2730,

96 7/6,

97 -3617/510,

98 43867/798,

99 -174611/330,

100 854513/138,

101 -236364091/2730,

102 8553103/6,

103 -23749461029/870,

104 8615841276005/14322])

106 res = 0

107 factorial_denom = 1

108 for i in range(1, nterm + 1):

109 factorial_denom *= ((2*i)*(2*i-1))

110 res += ((-1)**(i-1) * 2**(2*i) * (2**(2*i) - 1) *

111 B2n[i-1] / factorial_denom * var**(2*i-1))

112 return res