I have a calculation where i can sum or subtract something but this depends on a simple condition. My problem is, that I don't know how I can change the code, so i don't need to write the calculation twice just with the difference of the or -. Hopefully somebody can helf me. Thanks in advance.
public void changePrice(Stock stock, int amount, boolean isBuying) {
double roundRandomNumber = Math.round((0.5 Math.random()) * 100) / 100.00;
double newPrice;
//calculates plus or minus depending on the buyoption
if (isBuying) {
newPrice = Math.round((stock.getPrice() roundRandomNumber * 0.1 * amount) * 100) / 100.00;
} else {
newPrice = Math.round((stock.getPrice() - roundRandomNumber * 0.1 * amount) * 100) / 100.00;
}
if (newPrice > 0 && newPrice < 3000) {
stock.setPrice(newPrice);
}
}
CodePudding user response:
You can use a 1 or -1 coefficient based on isBuying value.
newPrice = Math.round((stock.getPrice() (isBuying ? 1.0 : -1.0) * roundRandomNumber * 0.1 * amount) * 100) / 100.00;
CodePudding user response:
You could try by extracting just the factor in the condition:
public void changePrice(Stock stock, int amount, boolean isBuying) {
double roundRandomNumber = Math.round((0.5 Math.random()) * 100) / 100.00;
double newPrice;
//calculates plus or minus depending on the buyoption
double factor;
if (isBuying) {
factor = 1.0
} else {
factor = -1.0
}
newPrice = Math.round((stock.getPrice() (factor * roundRandomNumber) * 0.1 * amount) * 100) / 100.00;
if (newPrice > 0 && newPrice < 3000) {
stock.setPrice(newPrice);
}
}
CodePudding user response:
I come up with substitution of roundRandomNumber yielding an expression with ( / 100) * 0.1 which can simplified to * 0.001.
Also round(0.5 x) can be ceil(x).
Or use 1 new Random().nextInt(100).
double roundRandomNumber = Math.ceil((Math.random()) * 100) * 0.001 * amount;
double newPrice = stock.getPrice();
if (isBuying) {
newPrice = roundRandomNumber;
} else {
newPrice -= roundRandomNumber;
}
newPrice = Math.round((newPrice * 100) / 100.00;
if (newPrice > 0 && newPrice < 3000) {
stock.setPrice(newPrice);
}
For the rest it is the reserved register principle: I do stepwise things to newPrice.
The boundary condition excludes 0, which is questionable.
Of course BigDecimal should be mentioned. The complexity basically stems from wanting fixed point arithmetic with floating point. Unless you need speed, BigDecimal code can be more readable, though verbose.
