Rounding a number to 10^ form JAVA - java

I have a random number such as 35 127 3658 45782 etc... I want to round them to 10^ form like 10 100 1000 10000. I can do it with this code:
Math.pow(10, (int)(Math.log10(number)) + 1);
But this code seems to me a bit complex and long for basic operation like that. Is there a better way to do it?

float t =10,number;
//scan a value for "number"
while(number/t > 1)
{
t = t * 10;
}
if( (number/t) % 1 >= 0.5)
System.out.println(t);
else
System.out.println(t/10);
Though it takes more lines, this is simple to understand.

Related

How to multiply a double by a percentage

Hello I was just wondering How I could perform this operation in java?
What I have done is incorrect, I may be looking at this wrong!, some help would be appreciated.
double result = n / n * 100 <= 100;
First of all, there are two operations, the first one is a math operation, it is before to the '<='. The second one, is a boolean operation, so you should think what is the purpose of that inequality (show the boolean result or the math result).
On the other hand, if you want to store that result you should do this:
boolean result = n/n * 100 <= 100;
Because, it is an inequality.
Because you are comparing the value of n / n * 100 to 100, the result would be a boolean (true/false).
If you want to accomplish something with this, you would do something like this:
double result = (n / n) * 1; //Because 100% is = to 1
if(result <= 1){
//Do stuff
}
If you wanted to use a different percentage, then you would just replace 1 with the difference of 1 and that percentage. For example, if your percentage was 75%, then you would multiply by 0.75.

How can I get the max decimal value of n-digit number in Java?

In our code, we have the maximum number of digits allowed (say, 8) in a decimal (as in base 10) number. How can I use this number to see if a possible value is within that range (0 to 99,999,999)?
If we were working with binary numbers, I'd do something like:
value < 1<<(MAX + 1)
but of course that won't work for decimal. I also considered something like:
Long.toString(value).length() < MAX
but that seems much too heavy.
if (value >= 0 && value < Math.pow(10, MAX))
Use log base 10 to get the number of digits in a base 10 number
if ((int)(Math.log10(value) + 1) <= MAX) {
...
}
If you don't have access to log10, you can use normal log to do this:
int length = (int)(Math.log(value) / Math.log(10)) + 1;
if (length <= MAX) {
...
}
Note this also works for any base, so using the second method above, you can replace the 10 with any base and you have the length of that number in the given base
You can take 10 to the (nth) power;
value < (Math.pow (10, num_digits))
… for positive integer fixnums; if you're more concerned with magnitude than sign, perhaps use the absolute value:
Math.abs(value) < (Math.pow (10, num_digits))
This, of course, doesn't apply to floating-point or BigDecimal values, but the same (analogous, using method calls) works for arbitrarily large bignums using BigInteger.
Would this work?
val>=0 && (value/1000000000)==0 ?

Computing Pi in Java

This weeks assignment in programming is to compute Pi in java using this as the basis for the assignment:
(for 80% of the marks):
USING A WHILE OR A DO-WHILE LOOP write a program to compute PI using the following equation:
PI = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) + ...
Allow the user to specify the number of terms (5 terms are shown) to use in the computation.
Each time around the loop only one extra term should be added to the estimate for PI.
(for 20% of the marks):
Alter your solution from part one so that the user is
allowed to specify the precision required between 1 and 8 digits
(i.e. the number of digits which are correct; e.g. to 5 digits PI is 3.14159),
rather than the number of terms. The condition on the loop should be altered so that it
continues until the required precision is obtained. Note that you need only submit this
second version of the program (assuming you have it working).
I'm only able to use the above method to compute Pi, as thats what the lecturer wants. Ive got this so far, although the code keeps giving me the same wrong answer for every even number and a different wrong answer for each odd number. Im still on part one as i havent got the right answer yet to be able to progress onto part 2.
All help would be great, as the program needs to be submitted by tueday.
Thanks in advance!
import java.util.Scanner;
public class ComputePI {
public static void main(String[] args) {
System.out.print( "Please enter the amount of decimal "
+ "digits of PI, you would like to set it too");
Scanner termScan = new Scanner( System.in );
int term = termScan.nextInt();
termScan.close();
double pi = 3.0;
int loopCount = 2;
int number = 2;
while ( loopCount <= term )
{
if (loopCount % 2 == 0)
{
pi = pi + ( 4.0/ ((number) * (number+1) * (number+2)) );
}
else
{
pi = pi - ( 4.0 / ((number) * (number+1) * (number+2)) );
}
number = number + 2;
loopCount++;
}
System.out.print( "The Value of Pi in " + term +
" terms is equal to " + pi);
}
}
I am not going to give you code (you can figure it out for yourself, I'm certain), but I'll give you the location for where to look for the problem.
In the negative terms, you are adding 2 to each number multiplied together. However, you are adding 2 to each number in every iteration of the loop: the numberXXX + 2 part should probably just be numberXXX.
You are now also incrementing the numberXXX variables when loopCount is 1. In fact, the if (loopCount == 1) part is unnecessary, since you already initialize pi. You should just remove the if block there and switch the loopCount % 2 == X blocks around.
I'll also give you general advice about things you might want to consider in your code.
You don't need constants like 4.0 to be in a variable. Just replace fourConstant with 4.0.
You don't need to use an else if for the third block: if loopCount % 2 is not 0 it is definitely 1.
loopCount can only get integer values, so it should probably be an int. A double just consumes extra memory (this is not too problematic here, but may be in large programs) and can in some cases lead to errors (too large numbers may cause rounding errors).
You don't need three variables for numberOne, numberTwo and numberThree; they can always be represented as numberOne, numberOne + 1 and numberOne + 2.
You are incrementing the variables numerOne,numberTwo,numberThree in case the loopCount = 1. In this case you should just continue the loop without incrementing this variables. So change this:
if (loopCount == 1 )
{
pi = 3.0;
}
in:
if (loopCount == 1 )
{
pi = 3.0;
loopCount++;
continue;
}
And change this:
pi = pi - ( fourConstant / ((numberOne+2)*(numberTwo+2)*(numberThree+2)));
into:
pi = pi - ( fourConstant / ((numberOne)*(numberTwo)*(numberThree)));
Or you could just initialize loop count to 2 and remove the first if.
Additionally it would be better is loopCount and term were integer variables instead of Double since they are going to hold only integer values.

value to the next thousand instead of nearest thousand

Sorry im new to java, currently i wanted to code the value to next thousand instead of nearest thousand. But i have no ideas how to do it. I tried Math.round but it's for roundest. Please guide me, any help would be appreciated .
Expected output that i looking for :
example 1) if the place values less than 999, it will direct change to 1000
May i know how can i code the math formula for this ?
You can use Math.ceil for this.
// A quick code example :)
int val = 1400;
val = (int) (Math.ceil(val / 1000.0) * 1000);
You need to write some custom code as follow
int leftdigit=value/1000;
int nextthousand=(leftdigit+1)*1000;
Here Kindly note Math.ceil returns double so you should use it properly as stated below as for integer value it won't work properly and integer division will be performed.
double data = 1100;
data = Math.ceil(data / 1000) * 1000;
System.out.println(data);
OUTPUT
2000.0
Conversion from integers to floats leads to chaos, as for the same bit size, float mantissa length will always be smaller than integer size (IEEE-754 float mantissa is 23 bits vs 31 bits for the integer). Converting a large integer to float back and forth will not give the same integer after the conversion.
So here using Math.ceil() may work for integers or small long ints, but will break for large long values (63 bits).
Better use the following code (only works for value > 0):
int ii = ((i - 1) / 1000 + 1) * 1000;
or for long int version:
long ii = ((i - 1) / 1000 + 1) * 1000;
Does not unnecessarily overflow, keep precision even for large values, and probably way faster!
Addenda
As an example, the following java code:
int largeint = Integer.MAX_VALUE - 63;
float fl = (float)largeint;
int largeint2 = (int)fl;
System.out.println(largeint);
System.out.println(largeint2);
Print:
2147483584
2147483647

Generating the list of random numbers with certain average difference

I have to generate a list of random numbers and they have to have a given average difference. For example, a given average difference is 10, so these numbers are good: 1 3 5 9 15 51. What I do, is multiply the given average difference by 2 and add 1. Like this:
while (i <= 50000)
{
i += Math.random() * givenAverageDiff * 2 + 1;
list.add(i);
}
But I never get 5000 or more. In fact, it's always 4,850 or less. Why? Let's say givenAverageDiff is 10. What's my mistake? How can I fix it?
P.S. Implementation in C or PHP is also good for me.
Because you are doing "+ 1".
Let us calculate the expected difference:
E(2*10*x+1)= 2*10*E(x)+1 = 2*10*0.5+1 = 10+1. So, on an average you will get 50000/11 numbers.
You need to pick something whose expected value is equal to 10. Change it to the following and it should work:
while (i <= 50000)
{
i += Math.random() * (givenAverageDiff-1) * 2 + 1;
list.add(i);
}
Think about it in terms of the ranges you create. With your current calculation,
i += Math.random() * givenAverageDiff * 2 + 1;
you are adding between 1 and 2*givenAverageDiff to your number. The sum of 1 through 2x is (2x)(2x+1)/2, and since there are 2x options we divide by 2x to get (2x)(2x+1)/(2*2x) = (2x+1)/2 = x + 0.5.
So what you want is to have 2x+1 options, which is easiest by using a range of [0,2*x]. You can get that by adding parenthesis:
i += Math.random() * (givenAverageDiff * 2 + 1);
If you want it to always increase, then you either need use a non-uniform distribution, or a uniform distribution with a smaller range. To get a range [n,2*x-n] use
i += Math.random() * ((givenAverageDiff - n) * 2 + 1) + n;
If you use a negative value for n you can widen the range, making it possible for numbers to decrease as well.

Categories