Skip to content

Commit bcbf479

Browse files
authored
Merge pull request rawify#22 from harrysarson/expm1
Implements expm1
2 parents a3194d4 + fdd85ff commit bcbf479

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

complex.js

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,38 @@
4545
return (Math.exp(x) - Math.exp(-x)) * 0.5;
4646
};
4747

48+
/**
49+
* Calculates cos(x) - 1 using Taylor series if x is small.
50+
*
51+
* @param {number} x
52+
* @returns {number} cos(x) - 1
53+
*/
54+
55+
const cosm1 = function(x) {
56+
const limit = Math.PI/4;
57+
if (x < -limit || x > limit) {
58+
return (Math.cos(x) - 1.0);
59+
}
60+
61+
let xx = x * x;
62+
return xx *
63+
(-0.5 + xx *
64+
(1/24 + xx *
65+
(-1/720 + xx *
66+
(1/40320 + xx *
67+
(-1/3628800 + xx *
68+
(1/4790014600 + xx *
69+
(-1/87178291200 + xx *
70+
(1/20922789888000)
71+
)
72+
)
73+
)
74+
)
75+
)
76+
)
77+
)
78+
};
79+
4880
const hypot = function(x, y) {
4981

5082
let a = Math.abs(x);
@@ -525,6 +557,30 @@
525557
tmp * Math.sin(this['im']));
526558
},
527559

560+
/**
561+
* Calculate the complex exponent and subtracts one.
562+
*
563+
* This may be more accurate than `Complex(x).exp().sub(1)` if
564+
* `x` is small.
565+
*
566+
* @returns {Complex}
567+
*/
568+
'expm1': function() {
569+
570+
/**
571+
* exp(a + i*b) - 1
572+
= exp(a) * (cos(b) + j*sin(b)) - 1
573+
= expm1(a)*cos(b) + cosm1(b) + j*exp(a)*sin(b)
574+
*/
575+
576+
const a = this['re'];
577+
const b = this['im'];
578+
579+
return new Complex(
580+
Math.expm1(a) * Math.cos(b) + cosm1(b),
581+
Math.exp(a) * Math.sin(b));
582+
},
583+
528584
/**
529585
* Calculate the natural log
530586
*

tests/complex.test.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,26 @@ var functionTests = [{
197197
set: "3 - 2i",
198198
fn: "exp",
199199
expect: "-8.358532650935372 - 18.263727040666765i"
200+
}, {
201+
set: "3 - 2i",
202+
fn: "expm1",
203+
expect: "-9.358532650935372 - 18.263727040666765i"
204+
}, {
205+
set: "0",
206+
fn: "expm1",
207+
expect: "0"
208+
}, {
209+
set: "1e-6",
210+
fn: "expm1",
211+
expect: "0.0000010000005000001665"
212+
}, {
213+
set: "1e-5 + 5i",
214+
fn: "expm1",
215+
expect: "-0.716334977900736 - 0.9589338639538314i"
216+
}, {
217+
set: "1.2e-7 - 2e-6i",
218+
fn: "expm1",
219+
expect: "1.1999800719976027e-7 - 0.000002000000239998681i"
200220
}, {
201221
set: "3",
202222
fn: "pow",

0 commit comments

Comments
 (0)