From 4d7d4c45fd76faf7d71339ba84d352e7b8841009 Mon Sep 17 00:00:00 2001 From: Sourabh Bhat Date: Thu, 25 Jan 2024 14:05:20 +0100 Subject: [PATCH] Added sqrt to DoubleArray --- src/main/util/DoubleArray.java | 2 ++ test/main/util/DoubleArrayTest.java | 16 ++++++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/main/util/DoubleArray.java b/src/main/util/DoubleArray.java index d655184..76bf185 100644 --- a/src/main/util/DoubleArray.java +++ b/src/main/util/DoubleArray.java @@ -99,6 +99,8 @@ public static double[] sqr(double[] array) { return apply(array, e -> e * e); } + public static double[] sqrt(double[] array) {return apply(array, Math::sqrt);} + public static double[] apply(double[] a1, double[] a2, DoubleBinaryOperator function) { double[] result = new double[a1.length]; diff --git a/test/main/util/DoubleArrayTest.java b/test/main/util/DoubleArrayTest.java index eda8ac2..327815a 100644 --- a/test/main/util/DoubleArrayTest.java +++ b/test/main/util/DoubleArrayTest.java @@ -2,11 +2,11 @@ import org.junit.Test; -import java.util.Arrays; import java.util.Random; import static main.util.TestHelper.assertThrows; -import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; public class DoubleArrayTest { @@ -126,4 +126,16 @@ public void dot_product_of_two_vectors() { assertEquals(dotProduct, DoubleArray.dot(v1, v2), 1e-15); } + + @Test + public void test_sqr() { + double[] v = {5, 10, 1, 3, 2, 1.2}; + assertArrayEquals(new double[]{25, 100, 1, 9, 4, 1.44}, DoubleArray.sqr(v), 1e-15); + } + + @Test + public void test_sqrt() { + double[] v = {25, 100, 9, 4}; + assertArrayEquals(new double[]{5, 10, 3, 2}, DoubleArray.sqrt(v), 1e-15); + } }