Java example for numbers

This commit is contained in:
YuCheng Hu 2020-02-24 16:13:20 -05:00
parent 5d7e2cb728
commit 13ddc8e390
32 changed files with 1877 additions and 0 deletions

View File

@ -0,0 +1,29 @@
package com.ossez.maths;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalDemo {
/** Calculate total amount to be paid for an item rounded to cents..
* @param quantity
* @param unitPrice
* @param discountRate
* @param taxRate
* @return
*/
public static BigDecimal calculateTotalAmount(BigDecimal quantity,
BigDecimal unitPrice, BigDecimal discountRate, BigDecimal taxRate) {
BigDecimal amount = quantity.multiply(unitPrice);
BigDecimal discount = amount.multiply(discountRate);
BigDecimal discountedAmount = amount.subtract(discount);
BigDecimal tax = discountedAmount.multiply(taxRate);
BigDecimal total = discountedAmount.add(tax);
// round to 2 decimal places using HALF_EVEN
BigDecimal roundedTotal = total.setScale(2, RoundingMode.HALF_EVEN);
return roundedTotal;
}
}

View File

@ -0,0 +1,51 @@
package com.ossez.maths;
import java.math.BigDecimal;
public class FloatingPointArithmetic {
public static void main(String[] args) {
double a = 13.22;
double b = 4.88;
double c = 21.45;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
double sum_ab = a + b;
System.out.println("a + b = " + sum_ab);
double abc = a + b + c;
System.out.println("a + b + c = " + abc);
double ab_c = sum_ab + c;
System.out.println("ab + c = " + ab_c);
double sum_ac = a + c;
System.out.println("a + c = " + sum_ac);
double acb = a + c + b;
System.out.println("a + c + b = " + acb);
double ac_b = sum_ac + b;
System.out.println("ac + b = " + ac_b);
double ab = 18.1;
double ac = 34.67;
double sum_ab_c = ab + c;
double sum_ac_b = ac + b;
System.out.println("ab + c = " + sum_ab_c);
System.out.println("ac + b = " + sum_ac_b);
BigDecimal d = new BigDecimal(String.valueOf(a));
BigDecimal e = new BigDecimal(String.valueOf(b));
BigDecimal f = new BigDecimal(String.valueOf(c));
BigDecimal def = d.add(e).add(f);
BigDecimal dfe = d.add(f).add(e);
System.out.println("d + e + f = " + def);
System.out.println("d + f + e = " + dfe);
}
}

View File

@ -0,0 +1,47 @@
package com.ossez.maths;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import org.apache.commons.math3.util.Precision;
import org.decimal4j.util.DoubleRounder;
public class Round {
private static final double PI = 3.1415d;
public static void main (String args[]) {
System.out.println("PI: " + PI);
System.out.printf("Value with 3 digits after decimal point %.3f %n", PI);
// OUTPUTS: Value with 3 digits after decimal point 3.142
DecimalFormat df = new DecimalFormat("###.###");
System.out.println(df.format(PI));
System.out.println(round(PI, 3));
System.out.println(roundNotPrecise(PI, 3));
System.out.println(roundAvoid(PI, 3));
System.out.println(Precision.round(PI, 3));
System.out.println(DoubleRounder.round(PI, 3));
}
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(Double.toString(value));
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
public static double roundNotPrecise(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
public static double roundAvoid(double value, int places) {
double scale = Math.pow(10, places);
double rounded = Math.round(value * scale) / scale;
return rounded;
}
}

View File

@ -0,0 +1,8 @@
package com.ossez.nth.root.calculator;
public class NthRootCalculator
{
public Double calculate(Double base, Double n) {
return Math.pow(Math.E, Math.log(base)/n);
}
}

View File

@ -0,0 +1,13 @@
package com.ossez.nth.root.main;
import com.ossez.nth.root.calculator.NthRootCalculator;
public class Main {
public static void main(String[] args) {
NthRootCalculator calculator = new NthRootCalculator();
Double base = Double.parseDouble(args[0]);
Double n = Double.parseDouble(args[1]);
Double result = calculator.calculate(base, n);
System.out.println("The " + n + " root of " + base + " equals to " + result + ".");
}
}

View File

@ -0,0 +1,67 @@
package com.ossez.numberofdigits;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.RunnerException;
public class Benchmarking {
public static void main(String[] args) throws RunnerException, IOException {
org.openjdk.jmh.Main.main(args);
}
@State(Scope.Thread)
public static class ExecutionPlan {
public int number = Integer.MAX_VALUE;
public int length = 0;
public NumberOfDigits numberOfDigits= new NumberOfDigits();
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void stringBasedSolution(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.stringBasedSolution(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void logarithmicApproach(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.logarithmicApproach(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void repeatedMultiplication(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.repeatedMultiplication(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void shiftOperators(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.shiftOperators(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void dividingWithPowersOf2(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.dividingWithPowersOf2(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void divideAndConquer(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.divideAndConquer(plan.number);
}
}

View File

@ -0,0 +1,97 @@
package com.ossez.numberofdigits;
public class NumberOfDigits {
public int stringBasedSolution(int number) {
int length = String.valueOf(number).length();
return length;
}
public int logarithmicApproach(int number) {
int length = (int) Math.log10(number) + 1;
return length;
}
public int repeatedMultiplication(int number) {
int length = 0;
long temp = 1;
while(temp <= number) {
length++;
temp *= 10;
}
return length;
}
public int shiftOperators(int number) {
int length = 0;
long temp = 1;
while(temp <= number) {
length++;
temp = (temp << 3) + (temp << 1);
}
return length;
}
public int dividingWithPowersOf2(int number) {
int length = 1;
if (number >= 100000000) {
length += 8;
number /= 100000000;
}
if (number >= 10000) {
length += 4;
number /= 10000;
}
if (number >= 100) {
length += 2;
number /= 100;
}
if (number >= 10) {
length += 1;
}
return length;
}
public int divideAndConquer(int number) {
if (number < 100000){
// 5 digits or less
if (number < 100){
// 1 or 2
if (number < 10)
return 1;
else
return 2;
}else{
// 3 to 5 digits
if (number < 1000)
return 3;
else{
// 4 or 5 digits
if (number < 10000)
return 4;
else
return 5;
}
}
} else {
// 6 digits or more
if (number < 10000000) {
// 6 or 7 digits
if (number < 1000000)
return 6;
else
return 7;
} else {
// 8 to 10 digits
if (number < 100000000)
return 8;
else {
// 9 or 10 digits
if (number < 1000000000)
return 9;
else
return 10;
}
}
}
}
}

View File

@ -0,0 +1,35 @@
package com.ossez.numberofdigits;
import org.apache.log4j.Logger;
public class NumberOfDigitsDriver {
private static NumberOfDigits numberOfDigits;
private static Logger LOG = Logger.getLogger(NumberOfDigitsDriver.class);
static {
numberOfDigits = new NumberOfDigits();
}
public static void main(String[] args) {
LOG.info("Testing all methods...");
long length = numberOfDigits.stringBasedSolution(602);
LOG.info("String Based Solution : " + length);
length = numberOfDigits.logarithmicApproach(602);
LOG.info("Logarithmic Approach : " + length);
length = numberOfDigits.repeatedMultiplication(602);
LOG.info("Repeated Multiplication : " + length);
length = numberOfDigits.shiftOperators(602);
LOG.info("Shift Operators : " + length);
length = numberOfDigits.dividingWithPowersOf2(602);
LOG.info("Dividing with Powers of 2 : " + length);
length = numberOfDigits.divideAndConquer(602);
LOG.info("Divide And Conquer : " + length);
}
}

View File

@ -0,0 +1,72 @@
package com.ossez.pairsaddupnumber;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
/**
* Find all different pairs of numbers in an array that add up to a given sum - Complexity O(n)
*/
public class DifferentPairs {
/**
* Show all different pairs using traditional "for" loop
*
* @param input - number's array
* @param sum - given sum
* @return - number's array with all existing pairs. This list will contain just one pair's element because
* the other one can be calculated with SUM - element_1 = element_2
*/
public static List<Integer> findPairsWithForLoop(int[] input, int sum) {
final List<Integer> allDifferentPairs = new ArrayList<>();
// Aux. hash map
final Map<Integer, Integer> pairs = new HashMap<>();
for (int i : input) {
if (pairs.containsKey(i)) {
if (pairs.get(i) != null) {
// Add pair to returned list
allDifferentPairs.add(i);
}
// Mark pair as added to prevent duplicates
pairs.put(sum - i, null);
} else if (!pairs.containsValue(i)) {
// Add pair to aux. hash map
pairs.put(sum - i, i);
}
}
return allDifferentPairs;
}
/**
* Show all different pairs using Java 8 stream API
*
* @param input - number's array
* @param sum - given sum
* @return - number's array with all existing pairs. This list will contain just one pair's element because
* the other one can be calculated with SUM - element_1 = element_2
*/
public static List<Integer> findPairsWithStreamApi(int[] input, int sum) {
final List<Integer> allDifferentPairs = new ArrayList<>();
// Aux. hash map
final Map<Integer, Integer> pairs = new HashMap<>();
IntStream.range(0, input.length).forEach(i -> {
if (pairs.containsKey(input[i])) {
if (pairs.get(input[i]) != null) {
// Add pair to returned list
allDifferentPairs.add(input[i]);
}
// Mark pair as added to prevent duplicates
pairs.put(sum - input[i], null);
} else if (!pairs.containsValue(input[i])) {
// Add pair to aux. hash map
pairs.put(sum - input[i], input[i]);
}
}
);
return allDifferentPairs;
}
}

View File

@ -0,0 +1,51 @@
package com.ossez.pairsaddupnumber;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
/**
* Find all existing pairs of numbers in an array that add up to a given sum - Complexity O(n^2) "Brute force"
*/
public class ExistingPairs {
/**
* Show all existing pairs using traditional "for" loop
*
* @param input - number's array
* @param sum - given sum
* @return - number's array with all existing pairs. This list will contain just one pair's element because
* the other one can be calculated with SUM - element_1 = element_2
*/
public static List<Integer> findPairsWithForLoop(int[] input, int sum) {
final List<Integer> allExistingPairs = new ArrayList<>();
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input.length; j++) {
if (j != i && (input[i] + input[j]) == sum) {
allExistingPairs.add(input[i]);
}
}
}
return allExistingPairs;
}
/**
* Show all existing pairs using Java 8 stream API
*
* @param input - number's array
* @param sum - given sum
* @return - number's array with all existing pairs. This list will contain just one pair's element because
* the other one can be calculated with SUM - element_1 = element_2
*/
public static List<Integer> findPairsWithStreamApi(int[] input, int sum) {
final List<Integer> allExistingPairs = new ArrayList<>();
IntStream.range(0, input.length).forEach(i ->
IntStream.range(0, input.length)
.filter(j -> i != j && input[i] + input[j] == sum)
.forEach(j -> allExistingPairs.add(input[i]))
);
return allExistingPairs;
}
}

View File

@ -0,0 +1,74 @@
package com.ossez.pairsaddupnumber;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class FindPairs {
public void execute(int[] input, int sum) {
final StringBuilder inputArray = new StringBuilder();
inputArray.append("{");
IntStream.range(0, input.length).forEach(i -> inputArray.append(input[i] + ", "));
inputArray.append("}");
System.out.println(" Given number array: " + inputArray.toString());
System.out.println(" Given sum: " + sum);
/* Call services */
getDifferentPairs(input, sum);
getExistingPairs(input, sum);
}
/**
* Print all existing pairs for the given inputs: input array & sum number
*/
private static void getExistingPairs(int[] input, int sum) {
List<Integer> pairs = new ArrayList<>();
System.out.println("~ All existing pairs ~");
/* Traditional FOR loop */
// Call method
pairs = ExistingPairs.findPairsWithForLoop(input, sum);
// Create a pretty printing
final StringBuilder output1 = new StringBuilder();
pairs.forEach((pair) -> output1.append("{" + pair + ", " + (sum - pair) + "}, "));
// Print result
System.out.println("Traditional \"for\" loop: " + output1.toString().substring(0, output1.length() - 2));
/* Java 8 stream API */
// Call the method
pairs = ExistingPairs.findPairsWithStreamApi(input, sum);
// Create a pretty printing
final StringBuilder output2 = new StringBuilder();
pairs.forEach((pair) -> output2.append("{" + pair + ", " + (sum - pair) + "}, "));
// Print result
System.out.println("Java 8 streams API: " + output2.toString().substring(0, output2.length() - 2));
}
/**
* Print all different pairs for the given inputs: input array & sum number
*/
private static void getDifferentPairs(int[] input, int sum) {
List<Integer> pairs = new ArrayList<>();
System.out.println("~ All different pairs ~");
/* Traditional FOR loop */
// Call method
pairs = DifferentPairs.findPairsWithForLoop(input, sum);
// Create a pretty printing
final StringBuilder output3 = new StringBuilder();
pairs.forEach((pair) -> output3.append("{" + pair + ", " + (sum - pair) + "}, "));
// Print result
System.out.println("Traditional \"for\" loop: " + output3.toString().substring(0, output3.length() - 2));
/* Java 8 stream API */
// Call method
pairs = DifferentPairs.findPairsWithStreamApi(input, sum);
// Create a pretty printing
final StringBuilder output4 = new StringBuilder();
pairs.forEach((pair) -> output4.append("{" + pair + ", " + (sum - pair) + "}, "));
// Print result
System.out.println("Java 8 streams API: " + output4.toString().substring(0, output4.length() - 2));
}
}

View File

@ -0,0 +1,36 @@
package com.ossez.random;
import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.DoubleStream;
public interface SecureRandomDemo {
public static void generateSecureRandomValues() {
SecureRandom sr = new SecureRandom();
int randomInt = sr.nextInt();
long randomLong = sr.nextLong();
float randomFloat = sr.nextFloat();
double randomDouble = sr.nextDouble();
boolean randomBoolean = sr.nextBoolean();
IntStream randomIntStream = sr.ints();
LongStream randomLongStream = sr.longs();
DoubleStream randomDoubleStream = sr.doubles();
byte[] values = new byte[124];
sr.nextBytes(values);
}
public static SecureRandom getSecureRandomForAlgorithm(String algorithm) throws NoSuchAlgorithmException {
if (algorithm == null || algorithm.isEmpty()) {
return new SecureRandom();
}
return SecureRandom.getInstance(algorithm);
}
}

View File

@ -0,0 +1,42 @@
package com.ossez.string;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class DoubleToString {
public static String truncateByCast(double d) {
return String.valueOf((int) d);
}
public static String roundWithStringFormat(double d) {
return String.format("%.0f", d);
}
public static String truncateWithNumberFormat(double d) {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0);
nf.setRoundingMode(RoundingMode.FLOOR);
return nf.format(d);
}
public static String roundWithNumberFormat(double d) {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0);
return nf.format(d);
}
public static String truncateWithDecimalFormat(double d) {
DecimalFormat df = new DecimalFormat("#,###");
df.setRoundingMode(RoundingMode.FLOOR);
return df.format(d);
}
public static String roundWithDecimalFormat(double d) {
DecimalFormat df = new DecimalFormat("#,###");
return df.format(d);
}
}

View File

@ -0,0 +1,6 @@
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,116 @@
package com.ossez.decimalformat;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import org.junit.Test;
public class DecimalFormatExamplesUnitTest {
double d = 1234567.89;
@Test
public void givenSimpleDecimal_WhenFormatting_ThenCorrectOutput() {
assertThat(new DecimalFormat("#.##", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
.isEqualTo("1234567.89");
assertThat(new DecimalFormat("0.00", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
.isEqualTo("1234567.89");
assertThat(new DecimalFormat("#########.###", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
.isEqualTo("1234567.89");
assertThat(new DecimalFormat("000000000.000", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
.isEqualTo("001234567.890");
}
@Test
public void givenSmallerDecimalPattern_WhenFormatting_ThenRounding() {
assertThat(new DecimalFormat("#.#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)).isEqualTo("1234567.9");
assertThat(new DecimalFormat("#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d)).isEqualTo("1234568");
}
@Test
public void givenGroupingSeparator_WhenFormatting_ThenGroupedOutput() {
assertThat(new DecimalFormat("#,###.#", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
.isEqualTo("1,234,567.9");
assertThat(new DecimalFormat("#,###", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
.isEqualTo("1,234,568");
}
@Test
public void givenMixedPattern_WhenFormatting_ThenCorrectOutput() {
assertThat(new DecimalFormat("The # number", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
.isEqualTo("The 1234568 number");
assertThat(new DecimalFormat("The '#' # number", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
.isEqualTo("The # 1234568 number");
}
@Test
public void givenLocales_WhenFormatting_ThenCorrectOutput() {
assertThat(new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
.isEqualTo("1,234,567.89");
assertThat(new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.ITALIAN)).format(d))
.isEqualTo("1.234.567,89");
assertThat(new DecimalFormat("#,###.##", DecimalFormatSymbols.getInstance(new Locale("it", "IT"))).format(d))
.isEqualTo("1.234.567,89");
}
@Test
public void givenE_WhenFormatting_ThenScientificNotation() {
assertThat(new DecimalFormat("00.#######E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
.isEqualTo("12.3456789E5");
assertThat(new DecimalFormat("000.000000E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
.isEqualTo("123.456789E4");
assertThat(new DecimalFormat("##0.######E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
.isEqualTo("1.23456789E6");
assertThat(new DecimalFormat("###.000000E0", new DecimalFormatSymbols(Locale.ENGLISH)).format(d))
.isEqualTo("1.23456789E6");
}
@Test
public void givenString_WhenParsing_ThenCorrectOutput() throws ParseException {
assertThat(new DecimalFormat("", new DecimalFormatSymbols(Locale.ENGLISH)).parse("1234567.89"))
.isEqualTo(1234567.89);
assertThat(new DecimalFormat("", new DecimalFormatSymbols(Locale.ITALIAN)).parse("1.234.567,89"))
.isEqualTo(1234567.89);
}
@Test
public void givenStringAndBigDecimalFlag_WhenParsing_ThenCorrectOutput() throws ParseException {
NumberFormat nf = new DecimalFormat("", new DecimalFormatSymbols(Locale.ENGLISH));
((DecimalFormat) nf).setParseBigDecimal(true);
assertThat(nf.parse("1234567.89")).isEqualTo(BigDecimal.valueOf(1234567.89));
}
}

View File

@ -0,0 +1,120 @@
package com.ossez.maths;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.Random;
import org.junit.jupiter.api.Test;
public class BigDecimalDemoUnitTest {
@Test
public void whenBigDecimalCreated_thenValueMatches() {
BigDecimal bdFromString = new BigDecimal("0.1");
BigDecimal bdFromCharArray = new BigDecimal(
new char[] { '3', '.', '1', '6', '1', '5' });
BigDecimal bdlFromInt = new BigDecimal(42);
BigDecimal bdFromLong = new BigDecimal(123412345678901L);
BigInteger bigInteger = BigInteger.probablePrime(100, new Random());
BigDecimal bdFromBigInteger = new BigDecimal(bigInteger);
assertEquals("0.1", bdFromString.toString());
assertEquals("3.1615", bdFromCharArray.toString());
assertEquals("42", bdlFromInt.toString());
assertEquals("123412345678901", bdFromLong.toString());
assertEquals(bigInteger.toString(), bdFromBigInteger.toString());
}
@Test
public void whenBigDecimalCreatedFromDouble_thenValueMayNotMatch() {
BigDecimal bdFromDouble = new BigDecimal(0.1d);
assertNotEquals("0.1", bdFromDouble.toString());
}
@Test
public void whenBigDecimalCreatedUsingValueOf_thenValueMatches() {
BigDecimal bdFromLong1 = BigDecimal.valueOf(123412345678901L);
BigDecimal bdFromLong2 = BigDecimal.valueOf(123412345678901L, 2);
BigDecimal bdFromDouble = BigDecimal.valueOf(0.1d);
assertEquals("123412345678901", bdFromLong1.toString());
assertEquals("1234123456789.01", bdFromLong2.toString());
assertEquals("0.1", bdFromDouble.toString());
}
@Test
public void whenEqualsCalled_thenSizeAndScaleMatched() {
BigDecimal bd1 = new BigDecimal("1.0");
BigDecimal bd2 = new BigDecimal("1.00");
assertFalse(bd1.equals(bd2));
}
@Test
public void whenComparingBigDecimals_thenExpectedResult() {
BigDecimal bd1 = new BigDecimal("1.0");
BigDecimal bd2 = new BigDecimal("1.00");
BigDecimal bd3 = new BigDecimal("2.0");
assertTrue(bd1.compareTo(bd3) < 0);
assertTrue(bd3.compareTo(bd1) > 0);
assertTrue(bd1.compareTo(bd2) == 0);
assertTrue(bd1.compareTo(bd3) <= 0);
assertTrue(bd1.compareTo(bd2) >= 0);
assertTrue(bd1.compareTo(bd3) != 0);
}
@Test
public void whenPerformingArithmetic_thenExpectedResult() {
BigDecimal bd1 = new BigDecimal("4.0");
BigDecimal bd2 = new BigDecimal("2.0");
BigDecimal sum = bd1.add(bd2);
BigDecimal difference = bd1.subtract(bd2);
BigDecimal quotient = bd1.divide(bd2);
BigDecimal product = bd1.multiply(bd2);
assertTrue(sum.compareTo(new BigDecimal("6.0")) == 0);
assertTrue(difference.compareTo(new BigDecimal("2.0")) == 0);
assertTrue(quotient.compareTo(new BigDecimal("2.0")) == 0);
assertTrue(product.compareTo(new BigDecimal("8.0")) == 0);
}
@Test
public void whenGettingAttributes_thenExpectedResult() {
BigDecimal bd = new BigDecimal("-12345.6789");
assertEquals(9, bd.precision());
assertEquals(4, bd.scale());
assertEquals(-1, bd.signum());
}
@Test
public void whenRoundingDecimal_thenExpectedResult() {
BigDecimal bd = new BigDecimal("2.5");
// Round to 1 digit using HALF_EVEN
BigDecimal rounded = bd
.round(new MathContext(1, RoundingMode.HALF_EVEN));
assertEquals("2", rounded.toString());
}
@Test
public void givenPurchaseTxn_whenCalculatingTotalAmount_thenExpectedResult() {
BigDecimal quantity = new BigDecimal("4.5");
BigDecimal unitPrice = new BigDecimal("2.69");
BigDecimal discountRate = new BigDecimal("0.10");
BigDecimal taxRate = new BigDecimal("0.0725");
BigDecimal amountToBePaid = BigDecimalDemo
.calculateTotalAmount(quantity, unitPrice, discountRate, taxRate);
assertEquals("11.68", amountToBePaid.toString());
}
}

View File

@ -0,0 +1,25 @@
package com.ossez.maths;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalImplUnitTest {
@Test
public void givenBigDecimalNumbers_whenAddedTogether_thenGetExpectedResult() {
BigDecimal serviceTax = new BigDecimal("56.0084578639");
serviceTax = serviceTax.setScale(2, RoundingMode.CEILING);
BigDecimal entertainmentTax = new BigDecimal("23.00689");
entertainmentTax = entertainmentTax.setScale(2, RoundingMode.FLOOR);
BigDecimal totalTax = serviceTax.add(entertainmentTax);
BigDecimal result = BigDecimal.valueOf(79.01);
Assert.assertEquals(result, totalTax);
}
}

View File

@ -0,0 +1,128 @@
package com.ossez.maths;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.math.BigInteger;
import java.util.Random;
import org.junit.jupiter.api.Test;
public class BigIntegerDemoUnitTest {
@Test
public void whenBigIntegerCreatedFromConstructor_thenExpectedResult() {
BigInteger biFromString = new BigInteger("1234567890987654321");
BigInteger biFromByteArray = new BigInteger(
new byte[] { 64, 64, 64, 64, 64, 64 });
BigInteger biFromSignMagnitude = new BigInteger(-1,
new byte[] { 64, 64, 64, 64, 64, 64 });
assertEquals("1234567890987654321", biFromString.toString());
assertEquals("70644700037184", biFromByteArray.toString());
assertEquals("-70644700037184", biFromSignMagnitude.toString());
}
@Test
public void whenLongConvertedToBigInteger_thenValueMatches() {
BigInteger bi = BigInteger.valueOf(2305843009213693951L);
assertEquals("2305843009213693951", bi.toString());
}
@Test
public void givenBigIntegers_whentCompared_thenExpectedResult() {
BigInteger i = new BigInteger("123456789012345678901234567890");
BigInteger j = new BigInteger("123456789012345678901234567891");
BigInteger k = new BigInteger("123456789012345678901234567892");
assertTrue(i.compareTo(i) == 0);
assertTrue(j.compareTo(i) > 0);
assertTrue(j.compareTo(k) < 0);
}
@Test
public void givenBigIntegers_whenPerformingArithmetic_thenExpectedResult() {
BigInteger i = new BigInteger("4");
BigInteger j = new BigInteger("2");
BigInteger sum = i.add(j);
BigInteger difference = i.subtract(j);
BigInteger quotient = i.divide(j);
BigInteger product = i.multiply(j);
assertEquals(new BigInteger("6"), sum);
assertEquals(new BigInteger("2"), difference);
assertEquals(new BigInteger("2"), quotient);
assertEquals(new BigInteger("8"), product);
}
@Test
public void givenBigIntegers_whenPerformingBitOperations_thenExpectedResult() {
BigInteger i = new BigInteger("17");
BigInteger j = new BigInteger("7");
BigInteger and = i.and(j);
BigInteger or = i.or(j);
BigInteger not = j.not();
BigInteger xor = i.xor(j);
BigInteger andNot = i.andNot(j);
BigInteger shiftLeft = i.shiftLeft(1);
BigInteger shiftRight = i.shiftRight(1);
assertEquals(new BigInteger("1"), and);
assertEquals(new BigInteger("23"), or);
assertEquals(new BigInteger("-8"), not);
assertEquals(new BigInteger("22"), xor);
assertEquals(new BigInteger("16"), andNot);
assertEquals(new BigInteger("34"), shiftLeft);
assertEquals(new BigInteger("8"), shiftRight);
}
@Test
public void givenBigIntegers_whenPerformingBitManipulations_thenExpectedResult() {
BigInteger i = new BigInteger("1018");
int bitCount = i.bitCount();
int bitLength = i.bitLength();
int getLowestSetBit = i.getLowestSetBit();
boolean testBit3 = i.testBit(3);
BigInteger setBit12 = i.setBit(12);
BigInteger flipBit0 = i.flipBit(0);
BigInteger clearBit3 = i.clearBit(3);
assertEquals(8, bitCount);
assertEquals(10, bitLength);
assertEquals(1, getLowestSetBit);
assertEquals(true, testBit3);
assertEquals(new BigInteger("5114"), setBit12);
assertEquals(new BigInteger("1019"), flipBit0);
assertEquals(new BigInteger("1010"), clearBit3);
}
@Test
public void givenBigIntegers_whenModularCalculation_thenExpectedResult() {
BigInteger i = new BigInteger("31");
BigInteger j = new BigInteger("24");
BigInteger k = new BigInteger("16");
BigInteger gcd = j.gcd(k);
BigInteger multiplyAndmod = j.multiply(k)
.mod(i);
BigInteger modInverse = j.modInverse(i);
BigInteger modPow = j.modPow(k, i);
assertEquals(new BigInteger("8"), gcd);
assertEquals(new BigInteger("12"), multiplyAndmod);
assertEquals(new BigInteger("22"), modInverse);
assertEquals(new BigInteger("7"), modPow);
}
@Test
public void givenBigIntegers_whenPrimeOperations_thenExpectedResult() {
BigInteger i = BigInteger.probablePrime(100, new Random());
boolean isProbablePrime = i.isProbablePrime(1000);
assertEquals(true, isProbablePrime);
}
}

View File

@ -0,0 +1,21 @@
package com.ossez.maths;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigInteger;
public class BigIntegerImplUnitTest {
@Test
public void givenBigIntegerNumbers_whenAddedTogether_thenGetExpectedResult() {
BigInteger numStarsMilkyWay = new BigInteger("8731409320171337804361260816606476");
BigInteger numStarsAndromeda = new BigInteger("5379309320171337804361260816606476");
BigInteger totalStars = numStarsMilkyWay.add(numStarsAndromeda);
BigInteger result = new BigInteger("14110718640342675608722521633212952");
Assert.assertEquals(result, totalStars);
}
}

View File

@ -0,0 +1,45 @@
package com.ossez.maths;
import java.math.BigDecimal;
import org.junit.Assert;
import org.junit.Test;
public class FloatingPointArithmeticUnitTest {
@Test
public void givenDecimalNumbers_whenAddedTogether_thenGetExpectedResult() {
double a = 13.22;
double b = 4.88;
double c = 21.45;
double result = 39.55;
double abc = a + b + c;
double acb = a + c + b;
Assert.assertEquals(result, abc, 0);
Assert.assertNotEquals(result, acb, 0);
double ab = 18.1;
double ac = 34.67;
double ab_c = ab + c;
double ac_b = ac + b;
Assert.assertEquals(result, ab_c, 0);
Assert.assertNotEquals(result, ac_b, 0);
BigDecimal d = new BigDecimal(String.valueOf(a));
BigDecimal e = new BigDecimal(String.valueOf(b));
BigDecimal f = new BigDecimal(String.valueOf(c));
BigDecimal sum = new BigDecimal("39.55");
BigDecimal def = d.add(e).add(f);
BigDecimal dfe = d.add(f).add(e);
Assert.assertEquals(0, def.compareTo(sum));
Assert.assertEquals(0, dfe.compareTo(sum));
Assert.assertNotEquals(0, sum.compareTo(new BigDecimal(String.valueOf(acb))));
}
}

View File

@ -0,0 +1,21 @@
package com.ossez.maths;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.jupiter.api.Test;
public class MathSinUnitTest {
@Test
public void givenAnAngleInDegrees_whenUsingToRadians_thenResultIsInRadians() {
double angleInDegrees = 30;
double sinForDegrees = Math.sin(Math.toRadians(angleInDegrees)); // 0.5
double thirtyDegreesInRadians = (double) 1 / 6 * Math.PI;
double sinForRadians = Math.sin(thirtyDegreesInRadians); // 0.5
assertThat(sinForDegrees, is(sinForRadians));
}
}

View File

@ -0,0 +1,71 @@
package com.ossez.maths;
import org.apache.commons.math3.util.Precision;
import org.decimal4j.util.DoubleRounder;
import org.junit.Assert;
import org.junit.Test;
public class RoundUnitTest {
private double value = 2.03456d;
private int places = 2;
private double delta = 0.0d;
private double expected = 2.03d;
@Test
public void givenDecimalNumber_whenRoundToNDecimalPlaces_thenGetExpectedResult() {
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertEquals(expected, Round.roundAvoid(value, places), delta);
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
places = 3;
expected = 2.035d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertEquals(expected, Round.roundAvoid(value, places), delta);
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
value = 1000.0d;
places = 17;
expected = 1000.0d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 92.23372036854776 !
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
value = 256.025d;
places = 2;
expected = 256.03d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 256.02 !
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 256.02 !
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 256.02 !
value = 260.775d;
places = 2;
expected = 260.78d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertNotEquals(expected, Round.roundNotPrecise(value, places), delta); // Returns: 260.77 !
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 260.77 !
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertNotEquals(expected, DoubleRounder.round(value, places), delta); // Returns: 260.77 !
value = 90080070060.1d;
places = 9;
expected = 90080070060.1d;
Assert.assertEquals(expected, Round.round(value, places), delta);
Assert.assertEquals(expected, Round.roundNotPrecise(value, places), delta);
Assert.assertNotEquals(expected, Round.roundAvoid(value, places), delta); // Returns: 9.223372036854776E9 !
Assert.assertEquals(expected, Precision.round(value, places), delta);
Assert.assertEquals(expected, DoubleRounder.round(value, places), delta);
}
}

View File

@ -0,0 +1,19 @@
package com.ossez.nth.root.calculator;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnitRunner;
public class NthRootCalculatorUnitTest {
private NthRootCalculator nthRootCalculator = new NthRootCalculator();
@Test
public void whenBaseIs125AndNIs3_thenNthRootIs5() {
Double result = nthRootCalculator.calculate(125.0, 3.0);
assertEquals(result, (Double) 5.0d);
}
}

View File

@ -0,0 +1,34 @@
package com.ossez.nth.root.main;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import static org.junit.Assert.assertEquals;
public class MainUnitTest {
@InjectMocks
private Main main;
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
}
@After
public void restoreStreams() {
System.setOut(originalOut);
}
@Test
public void givenThatTheBaseIs125_andTheExpIs3_whenMainIsCalled_thenTheCorrectResultIsPrinted() {
main.main(new String[]{"125.0", "3.0"});
assertEquals("The 3.0 root of 125.0 equals to 5.0.\n", outContent.toString().replaceAll("\r", ""));
}
}

View File

@ -0,0 +1,106 @@
package com.ossez.numberofdigits;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
@RunWith(Theories.class)
public class NumberOfDigitsIntegrationTest {
private static NumberOfDigits numberOfDigits;
static {
numberOfDigits = new NumberOfDigits();
}
@DataPoints
public static int[][] lowestIntegers()
{
return new int[][]{
{1, 1},
{2, 10},
{3, 100},
{4, 1000},
{5, 10000},
{6, 100000},
{7, 1000000},
{8, 10000000},
{9, 100000000},
{10, 1000000000}
};
}
@DataPoints
public static int[][] highestIntegers()
{
return new int[][]{
{1, 9},
{2, 99},
{3, 999},
{4, 9999},
{5, 99999},
{6, 999999},
{7, 9999999},
{8, 99999999},
{9, 999999999},
{10, Integer.MAX_VALUE}
};
}
@DataPoints
public static int[][] randomIntegers()
{
return new int[][]{
{1, 1},
{2, 14},
{3, 549},
{4, 1136},
{5, 25340},
{6, 134321},
{7, 1435432},
{8, 54234129},
{9, 113683912},
{10, 1534031982}
};
}
@Theory
public void givenDataPoints_whenStringBasedSolutionInvoked_thenAllPointsMatch(final int[] entry) {
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
Assert.assertEquals(entry[0], numberOfDigits.stringBasedSolution(entry[1]));
}
@Theory
public void givenDataPoints_whenLogarithmicApproachInvoked_thenAllPointsMatch(final int[] entry) {
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
Assert.assertEquals(entry[0], numberOfDigits.logarithmicApproach(entry[1]));
}
@Theory
public void givenDataPoints_whenRepeatedMultiplicationInvoked_thenAllPointsMatch(final int[] entry) {
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
Assert.assertEquals(entry[0], numberOfDigits.repeatedMultiplication(entry[1]));
}
@Theory
public void givenDataPoints_whenShiftOperatorsInvoked_thenAllPointsMatch(final int[] entry) {
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
Assert.assertEquals(entry[0], numberOfDigits.shiftOperators(entry[1]));
}
@Theory
public void givenDataPoints_whenDividingWithPowersOf2Invoked_thenAllPointsMatch(final int[] entry) {
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
Assert.assertEquals(entry[0], numberOfDigits.dividingWithPowersOf2(entry[1]));
}
@Theory
public void givenDataPoints_whenDivideAndConquerInvoked_thenAllPointsMatch(final int[] entry) {
Assume.assumeTrue(entry[0] > 0 && entry[1] > 0);
Assert.assertEquals(entry[0], numberOfDigits.divideAndConquer(entry[1]));
}
}

View File

@ -0,0 +1,39 @@
package com.ossez.pairsaddupnumber;
import org.junit.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class DifferentPairsUnitTest {
/* All different pairs */
@Test
public void whenTraditionalLoop_thenReturnAllDifferentPairs() {
/* Data */
final int[] input = {2, 4, 3, 3, 8};
final int sum = 6;
/* Call service */
final List<Integer> pairs = DifferentPairs.findPairsWithForLoop(input, sum);
/* Check results */
assertThat(pairs).hasSize(2).contains(4,3).doesNotContain(8);
}
@Test
public void whenStreamApi_thenReturnAllDifferentPairs() {
/* Data */
final int[] input = {2, 4, 3, 3, 8};
final int sum = 6;
/* Call service */
final List<Integer> pairs = DifferentPairs.findPairsWithStreamApi(input, sum);
/* Check results */
assertNotNull(pairs);
assertEquals(pairs.size(),2);
assertEquals(pairs.get(0), new Integer(4));
assertThat(pairs).hasSize(2).contains(4,3).doesNotContain(8);
}
}

View File

@ -0,0 +1,34 @@
package com.ossez.pairsaddupnumber;
import org.junit.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class ExistingPairsUnitTest {
/* All existing pairs */
@Test
public void whenTraditionalLoop_thenReturnAllExistingPairs() {
/* Data */
final int[] input = {2, 4, 3, 3, 8};
final int sum = 6;
/* Call service */
final List<Integer> pairs = ExistingPairs.findPairsWithForLoop(input, sum);
/* Check results */
assertThat(pairs).hasSize(4).contains(2,4,3,3).doesNotContain(8);
}
@Test
public void whenStreamApi_thenReturnAllExistingPairs() {
/* Data */
final int[] input = {2, 4, 3, 3, 8};
final int sum = 6;
/* Call service */
final List<Integer> pairs = ExistingPairs.findPairsWithStreamApi(input, sum);
/* Check results */
assertThat(pairs).hasSize(4).contains(2,4,3,3).doesNotContain(8);
}
}

View File

@ -0,0 +1,217 @@
package com.ossez.random;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.math3.random.RandomDataGenerator;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
import java.util.Random;
public class JavaRandomUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(JavaRandomUnitTest.class);
// tests - random long
@Test
public void givenUsingPlainJava_whenGeneratingRandomLongUnbounded_thenCorrect() {
final long generatedLong = new Random().nextLong();
LOG.debug("{}", generatedLong);
}
@Test
public void givenUsingApacheCommons_whenGeneratingRandomLongUnbounded_thenCorrect() {
final long generatedLong = new RandomDataGenerator().getRandomGenerator()
.nextLong();
LOG.debug("{}", generatedLong);
}
@Test
public void givenUsingPlainJava_whenGeneratingRandomLongBounded_thenCorrect() {
final long leftLimit = 1L;
final long rightLimit = 10L;
final long generatedLong = leftLimit + (long) (Math.random() * (rightLimit - leftLimit));
LOG.debug("{}", generatedLong);
}
@Test
public void givenUsingApacheCommons_whenGeneratingRandomLongBounded_thenCorrect() {
final long leftLimit = 10L;
final long rightLimit = 100L;
final long generatedLong = new RandomDataGenerator().nextLong(leftLimit, rightLimit);
LOG.debug("{}", generatedLong);
}
// tests - random int
@Test
public void givenUsingPlainJava_whenGeneratingRandomIntegerUnbounded_thenCorrect() {
final int generatedInteger = new Random().nextInt();
LOG.debug("{}", generatedInteger);
}
@Test
public void givenUsingPlainJava_whenGeneratingRandomIntegerBounded_thenCorrect() {
final int leftLimit = 1;
final int rightLimit = 10;
final int generatedInteger = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit));
LOG.debug("{}", generatedInteger);
}
@Test
public void givenUsingApache_whenGeneratingRandomIntegerUnbounded_thenCorrect() {
final Integer generatedInteger = new RandomDataGenerator().getRandomGenerator()
.nextInt();
LOG.debug("{}", generatedInteger);
}
@Test
public void givenUsingApache_whenGeneratingRandomIntegerBounded_thenCorrect() {
final int leftLimit = 1;
final int rightLimit = 10;
final int generatedInteger = new RandomDataGenerator().nextInt(leftLimit, rightLimit);
LOG.debug("{}", generatedInteger);
}
// tests - random float
@Test
public void givenUsingPlainJava_whenGeneratingRandomFloatUnbouned_thenCorrect() {
final float generatedFloat = new Random().nextFloat();
LOG.debug("{}", generatedFloat);
}
@Test
public void givenUsingApache_whenGeneratingRandomFloatUnbounded_thenCorrect() {
final float generatedFloat = new RandomDataGenerator().getRandomGenerator()
.nextFloat();
LOG.debug("{}", generatedFloat);
}
@Test
public void givenUsingPlainJava_whenGeneratingRandomFloatBouned_thenCorrect() {
final float leftLimit = 1F;
final float rightLimit = 10F;
final float generatedFloat = leftLimit + new Random().nextFloat() * (rightLimit - leftLimit);
LOG.debug("{}", generatedFloat);
}
@Test
public void givenUsingApache_whenGeneratingRandomFloatBounded_thenCorrect() {
final float leftLimit = 1F;
final float rightLimit = 10F;
final float randomFloat = new RandomDataGenerator().getRandomGenerator()
.nextFloat();
final float generatedFloat = leftLimit + randomFloat * (rightLimit - leftLimit);
LOG.debug("{}", generatedFloat);
}
// tests - random double
@Test
public void givenUsingPlainJava_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
final double generatedDouble = Math.random();
LOG.debug("{}", generatedDouble);
}
@Test
public void givenUsingApache_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
final double generatedDouble = new RandomDataGenerator().getRandomGenerator()
.nextDouble();
LOG.debug("{}", generatedDouble);
}
@Test
public void givenUsingPlainJava_whenGeneratingRandomDoubleBounded_thenCorrect() {
final double leftLimit = 1D;
final double rightLimit = 10D;
final double generatedDouble = leftLimit + new Random().nextDouble() * (rightLimit - leftLimit);
LOG.debug("{}", generatedDouble);
}
@Test
public void givenUsingApache_whenGeneratingRandomDoubleBounded_thenCorrect() {
final double leftLimit = 1D;
final double rightLimit = 100D;
final double generatedDouble = new RandomDataGenerator().nextUniform(leftLimit, rightLimit);
LOG.debug("{}", generatedDouble);
}
// tests - random String
@Test
public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() {
final byte[] array = new byte[7]; // length is bounded by 7
new Random().nextBytes(array);
final String generatedString = new String(array, Charset.forName("UTF-8"));
LOG.debug(generatedString);
}
@Test
public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() {
final int leftLimit = 97; // letter 'a'
final int rightLimit = 122; // letter 'z'
final int targetStringLength = 10;
final Random random = new Random();
final StringBuilder buffer = new StringBuilder(targetStringLength);
for (int i = 0; i < targetStringLength; i++) {
final int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1));
buffer.append((char) randomLimitedInt);
}
final String generatedString = buffer.toString();
LOG.debug(generatedString);
}
@Test
public void givenUsingApache_whenGeneratingRandomString_thenCorrect() {
final String generatedString = RandomStringUtils.random(10);
LOG.debug(generatedString);
}
@Test
public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() {
final String generatedString = RandomStringUtils.randomAlphabetic(10);
LOG.debug(generatedString);
}
@Test
public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() {
final String generatedString = RandomStringUtils.randomAlphanumeric(10);
LOG.debug(generatedString);
}
@Test
public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() {
final int length = 10;
final boolean useLetters = true;
final boolean useNumbers = false;
final String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);
LOG.debug(generatedString);
}
}

View File

@ -0,0 +1,100 @@
package com.ossez.removingdecimals;
import org.junit.Test;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.concurrent.TimeUnit;
/**
* This benchmark compares some of the approaches to formatting a floating-point
* value into a {@link String} while removing the decimal part.
*
* To run, simply run the {@link RemovingDecimalsManualTest#runBenchmarks()} test
* at the end of this class.
*
* The benchmark takes about 15 minutes to run. Since it is using {@link Mode#Throughput},
* higher numbers mean better performance.
*/
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5)
@Measurement(iterations = 20)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Benchmark)
public class RemovingDecimalsManualTest {
@Param(value = {"345.56", "345345345.56", "345345345345345345.56"}) double doubleValue;
NumberFormat nf;
DecimalFormat df;
@Setup
public void readyFormatters() {
nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0);
df = new DecimalFormat("#,###");
}
@Benchmark
public String whenCastToInt_thenValueIsTruncated() {
return String.valueOf((int) doubleValue);
}
@Benchmark
public String whenUsingStringFormat_thenValueIsRounded() {
return String.format("%.0f", doubleValue);
}
@Benchmark
public String whenUsingNumberFormat_thenValueIsRounded() {
nf.setRoundingMode(RoundingMode.HALF_UP);
return nf.format(doubleValue);
}
@Benchmark
public String whenUsingNumberFormatWithFloor_thenValueIsTruncated() {
nf.setRoundingMode(RoundingMode.FLOOR);
return nf.format(doubleValue);
}
@Benchmark
public String whenUsingDecimalFormat_thenValueIsRounded() {
df.setRoundingMode(RoundingMode.HALF_UP);
return df.format(doubleValue);
}
@Benchmark
public String whenUsingDecimalFormatWithFloor_thenValueIsTruncated() {
df.setRoundingMode(RoundingMode.FLOOR);
return df.format(doubleValue);
}
@Benchmark
public String whenUsingBigDecimalDoubleValue_thenValueIsTruncated() {
BigDecimal big = new BigDecimal(doubleValue);
big = big.setScale(0, RoundingMode.FLOOR);
return big.toString();
}
@Benchmark
public String whenUsingBigDecimalDoubleValueWithHalfUp_thenValueIsRounded() {
BigDecimal big = new BigDecimal(doubleValue);
big = big.setScale(0, RoundingMode.HALF_UP);
return big.toString();
}
@Test
public void runBenchmarks() throws Exception {
Options options = new OptionsBuilder()
.include(this.getClass().getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true).shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@ -0,0 +1,95 @@
package com.ossez.removingdecimals;
import org.junit.Test;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
/**
* Tests that demonstrate some different approaches for formatting a
* floating-point value into a {@link String} while removing the decimal part.
*/
public class RemovingDecimalsUnitTest {
private final double doubleValue = 345.56;
@Test
public void whenCastToInt_thenValueIsTruncated() {
String truncated = String.valueOf((int) doubleValue);
assertEquals("345", truncated);
}
@Test
public void givenALargeDouble_whenCastToInt_thenValueIsNotTruncated() {
double outOfIntRange = 6_000_000_000.56;
String truncationAttempt = String.valueOf((int) outOfIntRange);
assertNotEquals("6000000000", truncationAttempt);
}
@Test
public void whenUsingStringFormat_thenValueIsRounded() {
String rounded = String.format("%.0f", doubleValue);
assertEquals("346", rounded);
}
@Test
public void givenALargeDouble_whenUsingStringFormat_thenValueIsStillRounded() {
double outOfIntRange = 6_000_000_000.56;
String rounded = String.format("%.0f", outOfIntRange);
assertEquals("6000000001", rounded);
}
@Test
public void whenUsingNumberFormat_thenValueIsRounded() {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0);
nf.setRoundingMode(RoundingMode.HALF_UP);
String rounded = nf.format(doubleValue);
assertEquals("346", rounded);
}
@Test
public void whenUsingNumberFormatWithFloor_thenValueIsTruncated() {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0);
nf.setRoundingMode(RoundingMode.FLOOR);
String truncated = nf.format(doubleValue);
assertEquals("345", truncated);
}
@Test
public void whenUsingDecimalFormat_thenValueIsRounded() {
DecimalFormat df = new DecimalFormat("#,###");
df.setRoundingMode(RoundingMode.HALF_UP);
String rounded = df.format(doubleValue);
assertEquals("346", rounded);
}
@Test
public void whenUsingDecimalFormatWithFloor_thenValueIsTruncated() {
DecimalFormat df = new DecimalFormat("#,###");
df.setRoundingMode(RoundingMode.FLOOR);
String truncated = df.format(doubleValue);
assertEquals("345", truncated);
}
@Test
public void whenUsingBigDecimalDoubleValue_thenValueIsTruncated() {
BigDecimal big = new BigDecimal(doubleValue);
big = big.setScale(0, RoundingMode.FLOOR);
String truncated = big.toString();
assertEquals("345", truncated);
}
@Test
public void whenUsingBigDecimalDoubleValueWithHalfUp_thenValueIsRounded() {
BigDecimal big = new BigDecimal(doubleValue);
big = big.setScale(0, RoundingMode.HALF_UP);
String truncated = big.toString();
assertEquals("346", truncated);
}
}

View File

@ -0,0 +1,45 @@
package com.ossez.string;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class DoubleToStringUnitTest {
private static final double DOUBLE_VALUE = 3.56;
private static final String TRUNCATED_DOUBLE = "3";
private static final String ROUNDED_UP_DOUBLE = "4";
@Test
public void truncateByCastTest() {
assertThat(DoubleToString.truncateByCast(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
}
@Test
public void roundingWithStringFormatTest() {
assertThat(DoubleToString.roundWithStringFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
}
@Test
public void truncateWithNumberFormatTest() {
assertThat(DoubleToString.truncateWithNumberFormat(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
}
@Test
public void roundWithNumberFormatTest() {
assertThat(DoubleToString.roundWithNumberFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
}
@Test
public void truncateWithDecimalFormatTest() {
assertThat(DoubleToString.truncateWithDecimalFormat(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
}
@Test
public void roundWithDecimalFormatTest() {
assertThat(DoubleToString.roundWithDecimalFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
}
}