BigDecimal multiplication returns 0? - java

I'm a bit of a newbie at Java and I have to multiply 52 numbers with each other ranging anywhere from 0 to 2000. I already tried using *= without BigDecimal but the result gives me 0.0.
Here is my code:
BigDecimal productOfStock1 = BigDecimal.ZERO;
for(int k = 1; k <= N; k++){
for(int i = 1; i <= n; i++){
if (i == 1){
stockPrice[k][i] = stockZero*Math.pow(e, form + sigma*(randomno.nextGaussian()));
}
else {
stockPrice[k][i] = stockPrice[k][i-1]*Math.pow(e, form + sigma*(randomno.nextGaussian()));
}
//sumOfStock += stockPrice[k][i];
//productOfStock *= stockPrice[k][i];
productOfStock1 = productOfStock1.multiply(BigDecimal.valueOf(stockPrice[k][i]));
System.out.println(/*"Stock at [" + i + "] for N = " + N + " and path number " + k + " is " + */stockPrice[k][i]);
}
}
System.out.println(productOfStock1);
This gives me 0E-637 instead of the big number it is supposed to give me. Any help is appreciated.

BigDecimal productOfStock1 = BigDecimal.ZERO;
you need to initialize it with 1, because
0 * X = 0
(except for X= 1/0 :) )

Don't initialize productOfStock1 to 0, use 1 instead. Otherwise, you'll always be multiplying by 0.

Related

How to add a number to variable within String.format?

I want output like:
Dividend 1 : ...
Dividend 2 : ...
Dividend 3 : ...
Here is my code:
int i = 0;
while(i < dividendRates.length) {
System.out.println(String.format("Dividend %d : ", i) + (income * dividendRates[i]) );
i = i + 1;
}
But dividend number start with 0.
The easy way is just create new variable like 'int e = 1;' and use it, but I want to use variable 'i' and have output start with 1.
What should I do?
You can try the following code and I hope get the point:
int i = 1;
while( (i-1) < dividendRates.length) {
System.out.println(String.format("Dividend %d : ", i) + (income*dividendRates[i]) );
i = i + 1;
}

How can I detect integer overflow in integer multiplication

int base, power, result = 1;
for (int i = 1; i <= power; i++) {
result *= base;
}
System.out.println(base + " to the power of " + power + " result: " + result);
10 to the power of 9 result: 1000000000
but;
10 to the power of 10 result: 1410065408
In my application this is logically an error but how can I detect this error before the println?
for instance, when this error occurs, I want to print
"result data type is int 32bit, it must not exceed 2,147,483,647"
How can I catch these kinds of errors?
https://www.baeldung.com/java-overflow-underflow
I have found an enough answer here.
I have corrected my code like this:
try {
for (int i = 1; i <= power; i++) {
result = Math.multiplyExact(base, result);
}
} catch(ArithmeticException intSize) {
base = result = 0;
System.out.println("out of size int32: ")
}

Rolling dice project: code gives out of bounds exception below 7 and fails to save the first "Die Number"

I understand what out of bounds exception means, and how it happens, but I can't find out why it's happening in my code. Also, the output "Count for side 1" always states 0. This is my first post, but I think I am posting this right.
This is where I think the problem is.
System.out.println("Now rolling " + chosenRollNumber + " times. ");
int[] count = new int[chosenRollNumber];
for (x = 0; x < chosenRollNumber; x++) {
dieNumber = RNG(randomNum, min, max);
System.out.println("dieNumber " + dieNumber);
count[dieNumber]++;
}
System.out.println("Done rolling all dice");
for(x = 0; x < numberOfSides; x++) {
System.out.println("Count for side " + (x + 1) + " is " + count[x]); }
while(true) {
Method RNG(randomNum, min, max) is expected to return values in the range [min...max] (inclusive), while dieNumber as the index in count array needs to be in the range [0; numberOfSides), and the following relation exists numberOfSides == max - min + 1.
So, a correction is needed to transform dieNumber into a valid index:
System.out.println("Now rolling " + chosenRollNumber + " times. ");
int[] count = new int[numberOfSides];
for (x = 0; x < chosenRollNumber; x++) {
dieNumber = RNG(randomNum, min, max);
System.out.println("dieNumber " + dieNumber);
int dieIndex = (dieNumber - min) % numberOfSides;
count[dieIndex]++;
}

How to stop summing a harmonic series when it reaches a specified target in Java?

I'm a complete beginner in Java who just recently got introduced to loops. I'm trying to do write a program that reads in a target and finds the first n such that 1 + 1/2 + 1/3 + ... + 1/n > target. The problem supplied a code with the initialization of n and sum missing as well as the condition of while and its statements missing.
I'm able to work out how to make the harmonic series loop, but I'm not sure what to set n with to stop the loop when it exceeds the target.We've not learned about arrays in class yet..
import java.util.Scanner;
/**
This program computes how many steps the sum 1 + 1/2 + 1/3 + ...
needs to exceed a given target.
*/
public class ReciprocalSum
{
public static void main(String[] args)
{
double sum = 0;
int n = ???? ;
Scanner in = new Scanner(System.in);
System.out.print("Target: ");
double target = in.nextDouble();
int i = 0;
//Notes
// 1 + 1/2 + 1/3 + 1/4 + ..... 1/n
//Make a loop that repeats itself starting with n = 1 --> 1/1 + 1/2 + 1/3 + 1/4 + 1/n
// 1.0/n + (1.0/ n - 1) + (1.0/n-2) +.... if n =4 --> 1/4 + 1/3 + 1/2 + 1/1 as long as n >0
while ( n > 0)
{
sum += 1.0/n ;
n--;
}
System.out.println("n: " + n);
System.out.println("sum: " + sum);
}
}
n should be incremented in the loop (and therefore it should start at 0), and the loop should be exited when you reach the target:
int n = 0;
...
while (sum <= target)
{
n++;
sum += 1.0/n;
}
Because Java 8+ has lambdas, and you can generate a range 1 to n and perform your calculation and get the sum in one step. Basically, you could do
Scanner in = new Scanner(System.in);
System.out.print("Target: ");
double target = in.nextDouble(), sum = 1.0;
int n = 1;
while (sum < target) {
sum = IntStream.range(1, n).mapToDouble(i -> 1.0 / i).sum();
n++;
}
System.out.printf("n=%d, sum=%.2f%n", n, sum);
You can achieve that in this way by calculating sum of the series until its sum bigger than the target value:
double sum = 0;
int n = 1;
Scanner in = new Scanner(System.in);
System.out.print("Target: ");
double target = in.nextDouble();
while(sum <= target){
sum = sum + 1.0/n;
n = n + 1;
}
System.out.println(sum);

while nested in for loop. How does the decrement operator work?

I couldn't figure out how the decrement operator (e--)
works in code below, so i wrote the other class below it
to get the same result. I want to know how the decrement operator
achieves that result in the Power class. - Newbie.
int result, e;
for(int i=0; i < 10; i++) {
result = 1;
e = i;
while(e > 0) {
result *= 2;
e--;
}
System.out.println("2 to the " + i +
" power is " + result);
}
Code written to achieve same result
int result = 1;
for(int i=0; i < 10; i++) {
if (i > 0) {
result*=2;
}
System.out.println("2 to the " + i +
" power is " + result);
}
So the first example is resetting result for each iteration of the main for loop, so it needs to recalculate from scratch each time, where as the second example is keeping the previous computed value. The if in the second example is not needed is it.
The decrement operator modifies the variable on which it's called. So e-- is effectively e = e - 1 (except the overall result of the expression is different, see below).
This code:
result = 1;
e = i;
while(e > 0) {
result *= 2;
e--;
}
starts with result = 1 and then loops for i iterations doubling the value in result. Equivalent code using for which you seem more comfortable with:
result = 1;
for (e = 0; e < i; e++) {
result *= 2;
}
There are two forms of the decrement (and increment) operator: Prefix and postfix, depending on whether the operator is before (prefix) or after (postfix) its operand. Either could be used in the code you were asking about, because the only difference is the result of the expression.
Prefix: Suppose we have x = 5. The expression --x has the value 4: First we decrement x, then we take its new value as the result of the expression.
Postfix: Suppose we had x = 5 (again). The expression x-- has the value 5, with x ending up containing 4: First we grab the current value of x as the result of the expression, then we decrement it (because the -- is after x).
int x, r;
x = 5;
r = --x; // Prefix
System.out.println("r = " + r + ", x = " + x); // "r = 4, x = 4"
x = 5;
r = x--; // Postfix
System.out.println("r = " + r + ", x = " + x); // "r = 5, x = 4"
i figure out that by placing a System.out.println(e) i could "see" the variable "e" behavior in order to make sense of the decrement.
class Power {
public static void main(String args[]) {
int e;
int result;
for(int i=0; i < 10; i++) {
result =1 ;
e = i;
while(e > 0) {
System.out.println(e); // not part of the original program
result *= 2 ;
e--;
System.out.println(e); // not part of the original program
}
//System.out.println("2 to the " + i +
//" power is " + result);
}
This is the output:
C:\Users\enrique\Desktop\Hello.java>java Power: 1, 0, 2, 1, 1, 0, 3
e = 1(iteration 1), 2^1, e (1) decremented to 0, e = 2 (iteration 2), 2^2, e(2) decremented to 1, e = 1 re-enter The while but is ignored as 2^1 is already registered, e (1) decremented to 0, e = 3 (iteration 3), 2^3…

Categories

Resources