Decimal Format Issue Java - java

I wrote a program and I can't figure out how i should do the decimal format? I thought i was doing it right, apparently i can't do decimal format correctly. Can, someone help me with the decimal format?
Here is my code:
import java.text.DecimalFormat;
import java.util.*;
public class Mean {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
double[]x = new double[10];
int i;
for(i = 0;i < 10; i++){
x[i] = s.nextDouble();
}
double mean = mean(x, i);
double deviation = var(x);
System.out.println("The mean is " + mean);
System.out.println("The standard deviation is " + deviation);
}
public static double sum(double[] a) {
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
public static double mean(double[]x, double i){
if (x.length == 0) return Double.NaN;
double sum = sum(x);
return sum / x.length;
}
public static double var(double[] x) {
if (x.length == 0) return Double.NaN;
double avg = mean(x, 10);
double sum = 0.0;
for (int i = 0; i < x.length; i++) {
sum += (x[i] - avg) * (x[i] - avg);
}
DecimalFormat myFormatter = new DecimalFormat("#,##0.00");
return sum / myFormatter.format(Math.sqrt(x.length - 1));
}
}

Try this to format your double(s)... I also had to update you method var -
public static String formatDouble(double in) {
DecimalFormat myFormatter = new DecimalFormat(
"#,##0.00");
return myFormatter.format(in);
}
public static double var(double[] x) {
if (x.length == 0)
return Double.NaN;
double avg = mean(x);
double sum = 0.0;
for (int i = 0; i < x.length; i++) {
sum += (x[i] - avg) * (x[i] - avg);
}
return sum / Math.sqrt(x.length - 1);
}
public static void main(String[] args) {
double[] x = new double[] {
2000.20, 1000.10, 3000.30, 4000.40,5000.50,
6000.60,7000,70,8000.80,9000.90
};
double mean = mean(x);
double deviation = var(x);
System.out.println("The mean is "
+ formatDouble(mean));
System.out.println("The standard deviation is "
+ formatDouble(deviation));
}

The problem is the formatter return a String. you should return a String in the metod signature
public static String var(double[] x)
Also this line
return sum / myFormatter.format(Math.sqrt(x.length - 1));
Will not work if you are to return a String. You should do the calculations first, and then format it. Then return the formatted number
Edit: Try this, see if it works
public static String var(double[] x) {
if (x.length == 0)
return null;
double avg = mean(x, 10);
double sum = 0.0;
for (int i = 0; i < x.length; i++) {
sum += (x[i] - avg) * (x[i] - avg);
}
DecimalFormat myFormatter = new DecimalFormat("#,##0.00");
double result = sum / Math.sqrt(x.length - 1);
return myFormatter.format(result);
}
Then where you have this double deviation = var(x); replace it with String deviation = var(x);
Edit 2: complete code
import java.text.DecimalFormat;
import java.util.*;
public class Mean {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
double[]x = new double[10];
int i;
for(i = 0;i < 10; i++){
x[i] = s.nextDouble();
}
double mean = mean(x, i);
String deviation = var(x); // changed to String
System.out.println("The mean is " + mean);
System.out.println("The standard deviation is " + deviation);
}
public static double sum(double[] a) {
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
public static double mean(double[]x, double i){
if (x.length == 0) return Double.NaN;
double sum = sum(x);
return sum / x.length;
}
public static String var(double[] x) { // changed return
if (x.length == 0)
return null;
double avg = mean(x, 10);
double sum = 0.0;
for (int i = 0; i < x.length; i++) {
sum += (x[i] - avg) * (x[i] - avg);
}
DecimalFormat myFormatter = new DecimalFormat("#,##0.00");
double result = sum / Math.sqrt(x.length - 1);
return myFormatter.format(result);
}
}
Update: correct standard deviation formula
double result = Math.sqrt(sum / (x.length - 1));
^^

You need to format the double at the time of print.If you tried at var() function and then assign with double deviation then it will give numberformatException due to special character that returns by Var().You can run this code It will give you the output.
public static void main(String[] args) throws ParseException {
Scanner s = new Scanner(System.in);
double[]x = new double[10];
int i;
for(i = 0;i < 2; i++){
x[i] = s.nextDouble();
}
double mean = mean(x, i);
double deviation = var(x);
DecimalFormat myFormatter = new DecimalFormat("#,##0.00");
System.out.println("The mean is " + mean);
System.out.println("The standard deviation is " +myFormatter.format(deviation));
}
public static double sum(double[] a) {
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
public static double mean(double[]x, double i){
if (x.length == 0) return Double.NaN;
double sum = sum(x);
return sum / x.length;
}
public static double var(double[] x) {
if (x.length == 0) return Double.NaN;
double avg = mean(x, 10);
double sum = 0.0;
for (int i = 0; i < x.length; i++) {
sum += (x[i] - avg) * (x[i] - avg);
}
return sum / Math.sqrt(x.length - 1);
}

Related

How to find 10 random decimal numbers between min number and max number , the sum of random numbers should be X

to find 10 random decimal numbers between 7.00 and 13.00, the sum of the 10 random decimal numbers should be 100.
I have tried and I am getting the total sum but I am not getting the random number between range
public class TenRandomNumber {
private static final DecimalFormat df = new DecimalFormat("0.00");
public static void main(String args[]) {
double m = 10;
double n = 100;
double arr[] = new double[(int) m];
for (int i = 0; i < n; i++) {
double t=ThreadLocalRandom.current().nextDouble(7.00,13.00) * m;
arr[(int) t]++;
}
int totalCount = (int) m;
double total = 0;
for (int i = 0; i < totalCount; i++) {
if (i == (totalCount - 1)) {
arr[i] = Double.parseDouble(df.format(arr[i] - ThreadLocalRandom.current().nextDouble(0, 1)));
total = total + arr[i];
arr[i] = arr[i] + n - total;
} else {
arr[i] = Double.parseDouble(df.format(arr[i] - ThreadLocalRandom.current().nextDouble(0, 1)));
total = total + arr[i];
}
System.out.println(arr[i] + " ");
}
}
}
By dynamically calculating the feasible range of current random number, we can obtain the desired result in few tries.
class Main {
private static final DecimalFormat df = new DecimalFormat("0.00");
public static void main(String[] args) {
double[] result = safeGeneration(7, 13, 100, 10);
double sum = 0;
for (double d : result) sum += d;
System.out.println(Arrays.toString(result));
System.out.println("Sum: " + sum);
}
private static double[] safeGeneration(double min, double max, double totalSum, int count) {
// Some argument validation may be required here
while(true) {
try {
return generateRandoms(min, max, totalSum, count);
} catch (IllegalArgumentException e) {
// In case that bad randoms are given, try again.
}
}
}
private static double[] generateRandoms(double min, double max, double totalSum, int count) {
double currentSum = 0;
double[] array = new double[count];
for (int i = 0; i < count - 1; i++) {
// The minimum possible value for next random number that allows the rest numbers to stay in range.
double coerceMin = (totalSum - currentSum - max * (10 - i - 1));
// The maximum possible value for next random number that allows the rest numbers to stay in range.
double coerceMax = (totalSum - currentSum - min * (10 - i - 1));
coerceMin = Math.max(coerceMin, min);
coerceMax = Math.min(coerceMax, max);
double nextRandom = ThreadLocalRandom.current().nextDouble(coerceMin, coerceMax);
nextRandom = Double.parseDouble(df.format(nextRandom));
currentSum += nextRandom;
array[i] = nextRandom;
}
array[count - 1] = Double.parseDouble(df.format(totalSum - currentSum));
return array;
}
}
Sample output:
[8.05, 12.56, 12.97, 11.61, 9.4, 8.92, 9.07, 9.61, 7.54, 10.27]
Sum: 100.0

BigInteger Java How To Recreate A Formula

I tried to recreate this formula i am sure it's correct but the problem it gives me infinity and i need your help to transform it to BigInteger please help if possible
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner Input = new Scanner(System.in);
double X = Input.nextDouble();
double Y = Input.nextDouble();
double Ans = 0;
for (int I = 1; I <= 20; I++) {
for (int J = 1; J <= 20; J++) {
Ans += Math.log10(1 + Math.exp(Math.pow(-1, I + J) * (((Math.pow(I, 2) * X)) + (Math.pow(J, 2)) * Y)));
}
}
System.out.println(Ans);
}
}

Calculating Tarloy series in Java

I want to calculate the sum of this function ((-1)^n)*(x^2n)/(2.n!) but my program isn't working.I need your help.Here's what i tried:
public double getCos()
{
double Cos = 0;
for(int i=0;i<=n;i++)
{
Cos+=(power(x,i)/facto(n));
}
return Cos;
}
private double facto(int n)
{
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result*2;
}
private double power(int x,int n)
{
double power=Math.pow(-1,n)*Math.pow(x,2*n);
return power;
}
}
This is How You Make It I Just Fix Some Errors On Your Program :
public class Cos {
public static double getCos(double x) {
double Cos = 0;
for (int i = 0; i <= 5; i++) {
Cos += (power(-1, i) * power(x, 2*i)) / factorial(2*i) ;
}
return Cos;
}
public class Cos {
public static double getCos(double x) {
double Cos = 0;
for (int i = 0; i <= 5; i++) {
Cos += (power(-1, i) * power(x, 2*i)) / factorial(2*i) ;
}
return Cos;
}
private static double factorial(int n) {
int result = 1;
if( n == 0 || n == 1 )
return 1;
else {
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
}
private static double power(double x, int n) {
return Math.pow(x, n);
}
public static void main(String[] args) {
System.out.println("Test For The 3 Methods!");
System.out.println("5^2 : " + power(5, 2));
System.out.println("4! : " + factorial(4));
System.out.println("Cos(0.2) : " + getCos(0.2));
}
}
private static double power(double x, int n) {
return Math.pow(x, n);
}
public static void main(String[] args) {
System.out.println("Test For The 3 Methods!");
System.out.println("5^2 : " + power(5, 2));
System.out.println("4! : " + factorial(4));
System.out.println("Cos(0.2) : " + getCos(0.2));
}
}
From what I can tell, your difficulties are arising in your facto method. First of all, result was never properly declared (at least in the code provided). Furthermore, when 0 is passed for the first term, i=1 and therefore i<=0 evaluates false and the loop never executes. So what value would result have?
private double facto(int n) {
if(n==0) return 1.0;
double result = 0.0;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result*2;
}
This is How I Will Make This Exercise :
public class TaylorSeries {
static double power(double x,int n)
{
double p = 1;
for (int i = 1; i <= n ; i++) {
p = p*x;
}
return p;
}
// this is the best way to make factorial function by recursion
static int factorial(int n)
{
if(n == 1 || n == 0)
{
return 1;
}
else
{
return n*factorial(n - 1);
}
}
// i = 0 to i = 5 the 5 is for the summation
static double cos(double x)
{
double cos = 0;
for (int i = 0; i <= 5 ; i++) {
cos += ( power(-1, i) * power(x, 2*i) ) / ( factorial(2*i) );
}
return cos;
}
public static void main(String[] args) {
System.out.println("2^3 : " + power(2, 3));
System.out.println("5! : " + factorial(5));
// 20 means summation from 0 to 20
System.out.println("Cos(0.15) : " + cos(0.15));
}
}

What is wrong with my pi calculator?

I'm using Wallis' method to calculate pi, and I think I did it right. At least I thought I did anyway. I think the problem (output is 0)has to do with rounding and remainders, though I can't be sure. Here's the code:
import java.util.Scanner;
public class WallisPi {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = 2;
int b = 3;
int c = 1;
int pi = 0;
double acc = 0.0;
int n = scan.nextInt();
scan.close();
for (int i = 0; i <= n; i++) {
pi = (2 / 3) * c;
if (a > b) {
b += 2;
} else {
a += 2;
}
c = a / b;
}
pi *= 4;
System.out.println("The approximation of pi is " + pi + ".");
acc = Math.PI - pi;
System.out.println("It is " + acc + " off.");
}
}
Since posting this I've made some changes to the code, though it's still not quite functional. I get 2.666..., so there's something else at work here as well.
import java.util.Scanner;
public class WallisPi {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double a = 2.0;
double b = 3.0;
double c = 1.0;
double pi = 0;
double acc = 0.0;
int n = scan.nextInt();
scan.close();
for (int i = 0; i <= n; i++) {
pi = (2.0 / 3.0) * c;
if (a > b) {
b += 2;
} else {
a += 2;
}
c = a / b;
}
pi *= 4;
System.out.println("The approximation of pi is " + pi + ".");
acc = Math.PI - pi;
System.out.println("It is " + acc + " off.");
}
}
int a=2;
int b=3;
double pi=2;
for(int i=0;i<=n;i++){
pi *= (double)a/(double)b;
if(a>b){
b+=2;
} else {
a+=2;
}
}
pi*=2;
Using n = 4000 yields 3.141200
Here's the whole program, fixed:
import java.util.Scanner;
public class WallisPi {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
scan.close();
double pi = 2;
int a = 2;
int b = 3;
for (int i = 0; i <= n; i++){
pi *= (double) a / (double) b;
if (a > b) {
b += 2;
} else {
a += 2;
}
}
pi *= 2;
double acc = Math.PI - pi;
System.out.println("The approximation of pi is " + pi + ".");
System.out.println("It is " + acc + " off.");
}
}
Since your varibles are ints, all your divisions are integer divisions, omitting the fraction (and preserving only the whole part of the result). For accurate results, you should define your variables as doubles:
double a=2;
double b=3;
double c=1;
double pi=0;

Dividing longs which are returned by method - wrong values

I have two methods: power and factorial:
public static long pow(int x, int n) {
long p = x;
for (int i = 1; i < n; i++) {
p *= x;
}
return p;
}
public static long fact(int n) {
long s = n;
for (int i = 1; i < n; i++ ) {
s *= i;
}
return s;
}
that are returning longs. When I want to use them in new method evaluating Exponential function i get wrong results comparing to Math.exp(x). My code:
public static void exp(int x, double eps) {
int i = 1;
double pow = 1.0;
double fact = 1.0;
double sum = 0.0;
double temp;
do {
temp = pow/fact;
sum += temp;
pow = pow(x, i);
fact = fact(i);
i++;
}
while (temp > eps);
System.out.println("Check: " + Math.exp(x));
System.out.println("My: " + sum);
}
public static void main() {
int x = 10;
double eps = 0.0000000000001;
exp(x, eps);
}
and the output for x=10 is:
Check: 22026.465794806718
My: 21798.734894914145
the larger x, the bigger "loss of precision" (not exactly, because you can't really call it precise...).
The twist is, when methods power and factorial return double then the output is correct. Can anyone explain me how to make it work?
Methods pow and fact must return long and I must use them in exp (college assignment).
If you try this pow method:
public static long pow(int x, int n) {
long p = x;
System.out.println("Pow: "+x+","+n);
for (int i = 1; i < n; i++) {
p *= x;
System.out.println(p);
}
return p;
}
You get this output:
...
Pow: 10,20
100
1000
10000
...
...
1000000000000000
10000000000000000
100000000000000000
1000000000000000000
-8446744073709551616
7766279631452241920
The long value overflows: 10^20 is just too big to fit in a long.
Methods pow and fact must return long and I must use them in exp (college assignment).
Then there is not much you can do to fix it. You could throw an exception if eps is too small.
How large is x typically? It could be integer overflow. Try changing all the int arguments in pow and fact to be long instead.
Long data types can't handle decimal precision that's why you're values are wrong with long. Why don't you just have the functions return the double values?
Edit: Heres what I came up with:
public static long pow(int x, int n)
{
double p = x;
for (int i = 1; i < n; i++) {
p *= x;
}
return (long)p;
}
public static long fact(int n)
{
double s = n;
for (int i = 1; i < n; i++ ) {
s *= i;
}
return (long)s;
}
public static void exp(int x, double eps)
{
double pow = 1.0;
double fact = 1.0;
double sum = 0.0;
double temp;
for(int ii=1; ii < 100; ii++)
{
pow = pow(x, ii);
fact = fact(ii);
temp = (double)pow/(double)fact;
temp = temp == 1 ? 0 : temp;
sum += temp;
}
System.out.println("Check: " + Math.exp(x));
System.out.println("My: " + sum);
}
public static void main(final String[] args)
{
int x = 10;
double eps = 0.0000000000001;
exp(x, eps);
}
That's about the closest you're going to get without using the decimals.
Check: 22026.465794806718
My: 21946.785573087538

Categories