adding 2 BigDecimal values [duplicate] - java

This question already has answers here:
Addition for BigDecimal
(12 answers)
Closed 8 years ago.
class Point {
BigDecimal x;
BigDecimal y;
Point(double px, double py) {
x = new BigDecimal(px);
y = new BigDecimal(py);
}
void addFiveToCoordinate(String what) {
if (what.equals("x")) {
BigDecimal z = new BigDecimal(5);
x.add(z);
}
}
void show() {
System.out.print("\nx: " + getX() + "\ny: " + getY());
}
public BigDecimal getX() {
return x;
}
public BigDecimal getY() {
return y;
}
public static void main(String[] args) {
Point p = new Point(1.0, 1.0);
p.addFiveToCoordinate("x");
p.show();
}
}
Ok, I would like to add 2 BigDecimal values. I'm using constructor with doubles(cause I think that it's possible - there is a option in documentation). If I use it in main class, I get this:
x: 1
y: 1
When I use System.out.print to show my z variable i get this:
z: 5

BigDecimal is immutable. Every operation returns a new instance containing the result of the operation:
BigDecimal sum = x.add(y);
If you want x to change, you thus have to do
x = x.add(y);
Reading the javadoc really helps understanding how a class and its methods work.

Perhaps this is what you prefer:
BigDecimal z = new BigDecimal(5).add(x);
Every operation of BigDecimal returns a new BigDecimal but not change the current instance.

Related

Problems rounding to 2 decimal places [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
How to round a number to n decimal places in Java
(39 answers)
Closed 10 months ago.
I've used these posts as reference:
How to round a number to n decimal places in Java
round up to 2 decimal places in java? [duplicate]
After reading through the solutions to these question, I'm still having trouble rounding up to the hundredths place.
Here are what I've tried along with their outputs:
BigDecimal
import java.math.BigDecimal;
import java.math.RoundingMode;
public class RaceCarThread extends Thread {
private static boolean raceNow = false;
private int iterations;
private double lapsCompleted;
private boolean crash;
private int nbrOfCrashes;
// Default constructor
public RaceCarThread() {
super();
}
// Constructor for custom name
public RaceCarThread(String name) {
super(name);
raceNow = true;
lapsCompleted = 0;
crash = false;
nbrOfCrashes = 0;
}
public void run() {
while (!(lapsCompleted >= 17)) {
double randomNum = Math.random();
BigDecimal bd = new BigDecimal(randomNum).setScale(2, RoundingMode.HALF_EVEN);
randomNum = bd.doubleValue();
lapsCompleted = lapsCompleted + randomNum;
System.out.println(lapsCompleted);
}
}
}
10.31
10.5
11.13
11.850000000000001
12.810000000000002
13.570000000000002
14.200000000000003
15.080000000000004
15.800000000000004
16.200000000000003
16.790000000000003
17.430000000000003
Math.round(randomNum*100d) / 100d
public class RaceCarThread extends Thread {
private static boolean raceNow = false;
private int iterations;
private double lapsCompleted;
private boolean crash;
private int nbrOfCrashes;
// Default constructor
public RaceCarThread() {
super();
}
// Constructor for custom name
public RaceCarThread(String name) {
super(name);
raceNow = true;
lapsCompleted = 0;
crash = false;
nbrOfCrashes = 0;
}
public void run() {
while (!(lapsCompleted >= 17)) {
double randomNum = Math.random();
lapsCompleted = lapsCompleted + (Math.round(randomNum * 100d) / 100d);
System.out.println(lapsCompleted);
}
}
}
11.020000000000003
11.730000000000004
12.720000000000004
13.430000000000003
13.930000000000003
14.020000000000003
14.300000000000002
15.210000000000003
15.250000000000002
15.500000000000002
16.32
17.080000000000002
I'm unable to use DecimalFormat due to using the number in calculations.
Edit: The System.out.println(lapsCompleted) is just for checking the values and will be removed once I fix the decimals
If you're going to do calculations with your decimal values, you really need to use BigDecimal throughout. Never trust double or float to give accurate answers to calculations involving decimal values.
Also, when you create a BigDecimal from a double, don't use new BigDecimal(yourDouble), because that just puts the floating point error that's already in your double into the BigDecimal. It's generally much better to use BigDecimal.valueOf(yourDouble), which gives you the decimal value with the least number of decimal places that your double is close enough to. That sounds bad, but it's actually good, because you typically get the value that was used to create the double initially.
For example,
System.out.println(new BigDecimal(0.1)); // prints 0.1000000000000000055511151231257827021181583404541015625
System.out.println(BigDecimal.valueOf(0.1)); // prints 0.1

When to use Float vs Double in JAVA code? [duplicate]

This question already has answers here:
Float and double datatype in Java
(9 answers)
Closed 6 years ago.
Can someone show me an example of example how I could use Double in the following code?
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
int myFirstNumber = (5+10) + (6*8);//Declaring an integer myFirstNumber
int mySecondNumber = 10;
int myThirdNumber = 3;
int myTotal = myFirstNumber + mySecondNumber + myThirdNumber;
System.out.println(myFirstNumber);//prints variable myFirstNumber
System.out.println("myFirstNumber ");//
System.out.println(myTotal);
}
}
Use either float or double (or their boxed counterparts, Float and Double) when you need to deal with non-integer values. The code you posted has no apparent need for that, so it's hard to answer your question. But one possibility would be if you wanted to compute, say, the average of the three numbers:
public class HelloWorld { public static void main(String[] args) {
System.out.println("Hello, World!");
int myFirstNumber = (5+10) + (6*8);//Declaring an integer myFirstNumber
int mySecondNumber = 10;
int myThirdNumber = 3;
int myTotal = myFirstNumber + mySecondNumber + myThirdNumber;
float average = myTotal / 3.0f;
System.out.println(myFirstNumber);//prints variable myFirstNumber
System.out.println("myFirstNumber ");//
System.out.println(myTotal);
System.out.println(average);
}
As to when to use float vs. double (the title of your question), use double when you can tolerate less rounding error than you get with float.

How to work with an 'x' variable like in math?

How can I work with an 'x' variable like in math?
I need to write a code that determines a polynomial function. For example if the input data is 2, 4, 8, 9 then the function would be 2 + 4x + 8x^2 + 9x^3.
Now I do know how to process the input data etc. but I don't know how to declare a variable that has no value, for example I declared a variable x = double, but I still have to initialize it but I don't want to give x a value at this point yet?
So how can I write a method that for example returns 'x' to the power of something?
This is what I have at the moment (it still doesn't work of course)
public class Interpol {
public static void main(String []args) {
Scanner scanner = new Scanner(System.in);
//get user input (polynomial coefficients and interval values x1 and x2)
ArrayList<Double> polynomialCoefficients = new ArrayList<Double>();
int amountCoefficients = 0;
while (scanner.hasNextDouble()) {
polynomialCoefficients.add(scanner.nextDouble());
amountCoefficients++;
}
String in = scanner.next();
double x1 = scanner.nextDouble();
double x2 = scanner.nextDouble();
//call method f to determine the polynomial function
double x;
double[] termsFunction = new double[amountCoefficients];
for (int i = 0; i < polynomialCoefficients.size(); i++) {
termsFunction[i] = f(i, polynomialCoefficients.get(i));
}
//call method findaroot to determine the root
//print result
}
//determine function of which a root is to be found
public static double f(int i, double polynomialCoefficient) {
if (i == 0) {
return polynomialCoefficient;
}
double x;
return polynomialCoefficient * (Math.pow(x, i));
}
/* //rounds off d to 3 decimals
public static double rnd(double d) {
}
//returns a root in this interval, recursive function
public static double findaroot{double x1, double x2) {
}*/
}
You need to make a Class of objects that represent polynomials. The class will store the coefficients in an instance variable, and provide a method to evaluate the polynomial at a given value.
import java.util.*;
public class Foo {
public static void main(String[] args)
throws Exception
{
Scanner scanner = new Scanner(System.in);
//get user input (polynomial coefficients and interval values x1 and x2)
ArrayList<Double> polynomialCoefficients = new ArrayList<Double>();
int amountCoefficients = 0;
while (scanner.hasNextDouble()) {
polynomialCoefficients.add(scanner.nextDouble());
amountCoefficients++;
}
Polynomial polynomial = new Polynomial(polynomialCoefficients);
String in = scanner.next();
while (scanner.hasNextDouble()) {
double x = scanner.nextDouble();
System.out.println("f(" + x + ") = " + polynomial.evaluate(x));
}
}
static class Polynomial {
ArrayList<Double> _coefficients;
public Polynomial(ArrayList<Double> coefficients) {
_coefficients = coefficients;
}
public double evaluate(double x) {
double result = 0;
// This algorithm is called Horner’s rule. See Knuth.
for (int i = _coefficients.size() - 1; i>= 0; i--) {
result *= x;
result += _coefficients.get(i);
}
return result;
}
}
}
If I run this program and type 2 4 8 9 x 2.7, then it prints f(2.7) = 248.267, which is correct according to Wolfram Alpha.

How to write an .add() method? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
this is a homework problem, and I am having trouble understanding how I can create a .add() method in a class Distance.
class Distance has two integer instance variables:
private int feet;
private int inches;
It has a no argument constructor that initializes a Distance with zero feet and zero inches.
It has a two argument constructor that accepts two positive integers for feet and inches, and throws and exception if they are negative or if inches is greater than 11.
It also has get/set methods for the instance variables. My get/set methods:
public void setFeet(int f){
feet = f;
}
public void setInches(int in){
inches = in;
}
public int getFeet(){
return feet;
}
public int getInches(){
return inches;
}
My first question to anyone willing to answer: Is this how I am supposed to set up these get/set methods? I am unsure of myself.
My second problem lies with creating a method add() that adds another Distance object to itself. That is,
w1 = new Distance(4,9);
w2 = new Distance(3,6);
w1.add(w2); //w1 becomes 8 feet, 3 inches.
So far, I have this:
public int add(Distance d) {
int df = d.getFeet();
int di = d.getInches();
int a = this.feet;
int b = this.inches;
int c = a.getFeet();
int d = b.getInches();
int sumInches, sumFeet, temp;
sumInches =di + d;
sumFeet = df + c;
if (sumInches>11) {
temp = sumInches-11;
sumFeet = sumFeet+1;
sumInches = temp;
}
this.feet = sumFeet;
this.inches = sumInches;
}
But I am unsure if this would even compile (I don't have access to a computer where I can install a compiler right now). Can someone examine this and explain to me why this might be wrong?
int a = this.feet;
int b = this.inches;
Is a bit verbose...
int c = a.getFeet();
int d = b.getInches();
Won't compile, recall that primitive values (int, in our case) does not have methods.
Here's a solution, (added support for varargs, allowing infinite Distances):
public void add(Distance... distance) {
for(Distance d : distance) {
feet += d.getFeet();
if(inches + d.getInches >= 12)
feet++;
inches += d.getInches() % 12;
}
}
With this, you can easily add like this:
d1.add(d2, d3, d4, d5);
public void setInches(int in){
feet = in;
}
I assume that's a typo because you are assigning the in value to feet instead of inches.
public int getInches(){
return Inches;
}
Another typo. Java is case-sensitive so "Inches" is not the same as "inches".
Other than those, the getters/setters look fine.
As for the add() method... There's no reason to create those "a", "b", "c" and "d" variables
int a = this.feet;
int b = this.inches;
int c = a.getFeet();
int d = b.getInches();
You can just use this.feet and this.inches directly. It's not wrong per-se, just unnecessary and clutters the code. Also, I would highly recommend always creating meaningful variable names. "a", "b", "c" code is difficult to read. Variable names should be expressive.
Also, in your algorithm, you would need to subtract 12 from the summed inches.
So the add method could be written more succinctly like this:
public void add(Distance d)
{
int newFeet = this.feet + d.feet;
int newInches = this.inches + d.inches;
if (newInches > 11)
{
newFeet++;
newInches = newInches - 12;
}
this.feet = newFeet;
this.inches = newInches;
}
Personally, I would implement that logic by converting everything to inches and then using division and the modulus operator (%) to determine the feet and inches but I'll leave that as an exercise for you if you care.
My first question to anyone willing to answer: Is this how I am supposed to set up these get/set methods? I am unsure of myself.
Your getters/setter look correct; the point of them is to encapsulate the member variables so that they are not "modified" accidentally (restricting access). You probably want to initialize your member variables to some "default" value - in this case, I initialized them to 0 below.
Note: By default, the compiler will initialize them to 0.
private int feet = 0;
private int inches = 0;
public void setFeet(int f){
feet = f;
}
public void setInches(int in){
feet = in;
}
public int getFeet(){
return feet;
}
public int getInches(){
return inches;
}
My second problem lies with creating a method add().
About your "add" method, you probably want to change your local variables to be something more "descriptive", it will help "readability" and "maintainability" in the long run.
Since your "Distance" class already contains the member variables "feet" and "inches", there is no point of setting these values to a local variable. You can just access them directly -- along with any of the class's getters/setters.
public int add(Distance newDistance) {
int newDistanceFeet = newDistance.getFeet();
int newDistanceInches = newDistance.getInches();
int sumInches = newDistanceInches + this.getInches();
int sumFeet = newDistanceFeet + this.getFeet();
// Now we can check to see if any conversion are needed.. Note: 12 inches = 1 foot
//
sumInches += (sumInches % 12);
sumFeet += (sumInches / 12);
// Now set the newly added inches/feet to the class's member variables
//
this.setFeet(sumFeet);
this.setInches(sumInches);
}
Update your add() to :-
public int add(Distance d) {
int df = d.getFeet();
int di = d.getInches();
int a = this.feet;
int b = this.inches;
ERROR : c and d are integers and not Distance objects. You don't require c and d integers.
int sumInches, sumFeet, temp;
sumInches =di + b;
sumFeet = df + a;
if (sumInches>11) {
temp = sumInches-11;
sumFeet = sumFeet+1;
sumInches = temp;
}
this.feet = sumFeet;
this.inches = sumInches;
Your problem is here,
int a = this.feet;
int b = this.inches;
int c = a.getFeet();
int d = b.getInches();
Since a and b are int variable. They do not have getFeet() and getInches() method.
Change your add() method to
public int add(Distance d) {
int df = d.getFeet();
int di = d.getInches();
int sumInches, sumFeet, temp;
sumInches =di + this.inches;
sumFeet = df + this.feet;
if (sumInches>11) {
temp = sumInches-11;
sumFeet = sumFeet+1;
sumInches = temp;
}
this.feet = sumFeet;
this.inches = sumInches;
}
The basic idea is correct but you were doing some things wrong, consider instead:
public int add( Distance d ){
feet += d.feet;
inches += d.inches;
if( inches >= 12 ){
inches = inches - 12;
feet++;
}
}
The biggest issue i saw was
int a = this.feet;
int d = a.getFeet();
here a is an int not a Distance object hence you cant call getFeet()
Since it is a homework problem, I am not providing the complete solution. Since you have attempted the add method, I will optimize it further and provide the same here with comments
public void add(Distance distance) {
int extraFeet=0; /*Intializing the extra Feet*/
extraFeet = (this.inches+distance.getInches())/11; /*Calculating the additional feet*/
if(extraFeet >0)
this.inches = (this.inches+distance.getInches())%11; /*if extra feet is greater than zero thn the remainder is the inches*/
else
this.inches +=distance.getInches(); /*else teh remainder is the sum of the inches*/
this.feet += (distance.getFeet()+extraFeet);
}

Find the max of 3 numbers in Java with different data types

Say I have the following three constants:
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
I want to take the three of them and use Math.max() to find the max of the three but if I pass in more then two values then it gives me an error. For instance:
// this gives me an error
double maxOfNums = Math.max(MY_INT1, MY_INT2, MY_DOUBLE2);
Please let me know what I'm doing wrong.
Math.max only takes two arguments. If you want the maximum of three, use Math.max(MY_INT1, Math.max(MY_INT2, MY_DOUBLE2)).
you can use this:
Collections.max(Arrays.asList(1,2,3,4));
or create a function
public static int max(Integer... vals) {
return Collections.max(Arrays.asList(vals));
}
If possible, use NumberUtils in Apache Commons Lang - plenty of great utilities there.
https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/math/NumberUtils.html#max(int[])
NumberUtils.max(int[])
Math.max only takes two arguments, no more and no less.
Another different solution to the already posted answers would be using DoubleStream.of:
double max = DoubleStream.of(firstValue, secondValue, thirdValue)
.max()
.getAsDouble();
Without using third party libraries, calling the same method more than once or creating an array, you can find the maximum of an arbitrary number of doubles like so
public static double max(double... n) {
int i = 0;
double max = n[i];
while (++i < n.length)
if (n[i] > max)
max = n[i];
return max;
}
In your example, max could be used like this
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
public static void main(String[] args) {
double maxOfNums = max(MY_INT1, MY_INT2, MY_DOUBLE1);
}
Java 8 way. Works for multiple parameters:
Stream.of(first, second, third).max(Integer::compareTo).get()
I have a very simple idea:
int smallest = Math.min(a, Math.min(b, Math.min(c, d)));
Of course, if you have 1000 numbers, it's unusable, but if you have 3 or 4 numbers, its easy and fast.
Regards,
Norbert
Like mentioned before, Math.max() only takes two arguments. It's not exactly compatible with your current syntax but you could try Collections.max().
If you don't like that you can always create your own method for it...
public class test {
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
public static void main(String args[]) {
double maxOfNums = multiMax(MY_INT1, MY_INT2, MY_DOUBLE1);
}
public static Object multiMax(Object... values) {
Object returnValue = null;
for (Object value : values)
returnValue = (returnValue != null) ? ((((value instanceof Integer) ? (Integer) value
: (value instanceof Double) ? (Double) value
: (Float) value) > ((returnValue instanceof Integer) ? (Integer) returnValue
: (returnValue instanceof Double) ? (Double) returnValue
: (Float) returnValue)) ? value : returnValue)
: value;
return returnValue;
}
}
This will take any number of mixed numeric arguments (Integer, Double and Float) but the return value is an Object so you would have to cast it to Integer, Double or Float.
It might also be throwing an error since there is no such thing as "MY_DOUBLE2".
int first = 3;
int mid = 4;
int last = 6;
//checks for the largest number using the Math.max(a,b) method
//for the second argument (b) you just use the same method to check which //value is greater between the second and the third
int largest = Math.max(first, Math.max(last, mid));
You can do like this:
public static void main(String[] args) {
int x=2 , y=7, z=14;
int max1= Math.max(x,y);
System.out.println("Max value is: "+ Math.max(max1, z));
}
if you want to do a simple, it will be like this
// Fig. 6.3: MaximumFinder.java
// Programmer-declared method maximum with three double parameters.
import java.util.Scanner;
public class MaximumFinder
{
// obtain three floating-point values and locate the maximum value
public static void main(String[] args)
{
// create Scanner for input from command window
Scanner input = new Scanner(System.in);
// prompt for and input three floating-point values
System.out.print(
"Enter three floating-point values separated by spaces: ");
double number1 = input.nextDouble(); // read first double
double number2 = input.nextDouble(); // read second double
double number3 = input.nextDouble(); // read third double
// determine the maximum value
double result = maximum(number1, number2, number3);
// display maximum value
System.out.println("Maximum is: " + result);
}
// returns the maximum of its three double parameters
public static double maximum(double x, double y, double z)
{
double maximumValue = x; // assume x is the largest to start
// determine whether y is greater than maximumValue
if (y > maximumValue)
maximumValue = y;
// determine whether z is greater than maximumValue
if (z > maximumValue)
maximumValue = z;
return maximumValue;
}
} // end class MaximumFinder
and the output will be something like this
Enter three floating-point values separated by spaces: 9.35 2.74 5.1
Maximum is: 9.35
References Java™ How To Program (Early Objects), Tenth Edition
Simple way without methods
int x = 1, y = 2, z = 3;
int biggest = x;
if (y > biggest) {
biggest = y;
}
if (z > biggest) {
biggest = z;
}
System.out.println(biggest);
// System.out.println(Math.max(Math.max(x,y),z));

Categories

Resources