Skip to content

Commit

Permalink
More numerically stable compute_k
Browse files Browse the repository at this point in the history
The formula for `compute_k` gets unstable for bias values just greater
than 1. This patch applies a more stable approximation (based on the
Taylors series expansion).

Fixes linebender#9
  • Loading branch information
raphlinus committed Dec 27, 2020
1 parent 0d74dac commit 3d1de42
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/hyperbezier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,10 @@ fn integrate_basis(bias: f64, s: f64) -> f64 {
fn compute_k(bias: f64) -> f64 {
if bias <= 1.0 {
bias * 2.0
} else if bias < 1.0007 {
let a = bias - 1.0;
// A few terms of the Taylors series expansion of the formula below.
2.0 + 4.0 / 3.0 * a + 11.0 / 9.0 * a * a
} else {
let a = (bias - 1.0).min(MAX_A);
// Reciprocal of integral
Expand Down Expand Up @@ -302,7 +306,7 @@ pub(crate) fn compute_k_inv(k: f64) -> f64 {

#[test]
fn test_k() {
for k in &[0.0, 1.0, 2.0, 3.0, 5.0, 10.0, 20.0] {
for k in &[0.0, 1.0, 2.0, 2.000001, 3.0, 5.0, 10.0, 20.0] {
let bias = compute_k_inv(*k);
let actual_k = compute_k(bias);
assert!((k - actual_k).abs() < 1e-5);
Expand Down

0 comments on commit 3d1de42

Please sign in to comment.