Skip to content

Commit 788a43a

Browse files
authored
Merge pull request mathnet#887 from delicioustuna/specialfunction-log1p
add log1p function
2 parents efb8748 + f817566 commit 788a43a

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

src/Numerics.Tests/SpecialFunctionsTests/SpecialFunctionsTests.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,5 +311,26 @@ public void Logistic(double p, double x)
311311
{
312312
AssertHelpers.AlmostEqualRelative(x, SpecialFunctions.Logistic(p), 14);
313313
}
314+
315+
/// <summary>
316+
/// Log1p function.
317+
/// </summary>
318+
/// <param name="y">Expected value.</param>
319+
/// <param name="x">Input X value.</param>
320+
[TestCase(-1.0, double.NegativeInfinity)]
321+
[TestCase(-0.01, -0.010050335853501442)]
322+
[TestCase(-0.0001, -0.00010000500033335834)]
323+
[TestCase(-1.0e-6, -1.0000005000003334e-6)]
324+
[TestCase(-1.0e-8, -1.0000000050000001e-8)]
325+
[TestCase(0.0, 0.0)]
326+
[TestCase(1.0e-8, 9.999999950000001e-9)]
327+
[TestCase(1.0e-6, 9.999995000003334e-7)]
328+
[TestCase(0.0001, 9.999500033330834e-5)]
329+
[TestCase(0.01, 0.009950330853168083)]
330+
[TestCase(1.0, 0.6931471805599453)]
331+
public void Log1p(double x, double y)
332+
{
333+
AssertHelpers.AlmostEqualRelative(y, SpecialFunctions.Log1p(x), 14);
334+
}
314335
}
315336
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
5+
namespace MathNet.Numerics
6+
{
7+
/// <summary>
8+
/// This partial implementation of the SpecialFunctions class contains all methods related to the log1p function.
9+
/// </summary>
10+
public static partial class SpecialFunctions
11+
{
12+
/// <summary>
13+
/// Computes ln(1+x) with good relative precision when |x| is small
14+
/// </summary>
15+
/// <param name="x">The parameter for which to compute the log1p function. Range: x > 0.</param>
16+
public static double Log1p(double x)
17+
{
18+
double y0 = Math.Log(1.0 + x);
19+
20+
if ((-0.2928 < x) && (x < 0.4142))
21+
{
22+
double y = y0;
23+
24+
if (y == 0.0)
25+
{
26+
y = 1.0;
27+
}
28+
else if ((y < -0.69) || (y > 0.4))
29+
{
30+
y = (Math.Exp(y) - 1.0) / y;
31+
}
32+
else
33+
{
34+
double t = y / 2.0;
35+
y = Math.Exp(t) * Math.Sinh(t) / t;
36+
}
37+
38+
double s = y0 * y;
39+
double r = (s - x) / (s + 1.0);
40+
y0 = y0 - r * (6 - r) / (6 - 4 * r);
41+
}
42+
43+
return y0;
44+
}
45+
}
46+
}

0 commit comments

Comments
 (0)