Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Question That Needs To Be Solved: http://i62.tinypic.com/23rtieb.png
I have this problem I need to solve using Java. However I tried but was not able to. Here is what I have done so far.
public class Cirlce {
public static void main(String[] args) {
int counter = 0;
double pi = 0;
final String piCharacter = "\u03C0";
double num = 10000;
int e = 0;
for (int i = 0; i < 10000; i++) {
// r^2 = x^2 + y^2
double dx = Math.random();
double dy = Math.random();
double r = Math.sqrt(dx * dx + dy * dy);
if (r < 1) {
counter++;
pi = 4 * counter / 1000;
}
e++;
if (e == counter) {
System.out.println(pi);
counter += 1000;
}
System.out.println("The Approximated Value Of " + piCharacter + " is: " + pi);
}
}
}
The answer is that I need 10 outputs that are close to the value of pi.
One problem is in this line:
pi = 4 * counter / 1000;
4, counter and 1000 are all int, so you are doing integer arithmetic here. You'll need to make at least one of the values a double, for example:
pi = 4.0 * counter / 1000;
There are some other errors. For example, why are you doing counter += 1000;? Cleanup your code and make sure you understand exactly what each statement does.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
help me to understand this code
public class Exercise12 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input a number: ");
int n = in.nextInt();
printMatrix(n);
}
public static void printMatrix(int n) {
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
System.out.printin((int)(Math.random() * 2) + " ");
}
System.out.println();
}
}
}
Math.random() returns a number between 0.0 (inclusive) and 1.0 (exclusive).
Therefore (Math.random() * 2) is a number between 0.0 (inclusive) and 2.0 (exclusive).
Therefore (int)(Math.random() * 2) is either 0 or 1:
If (Math.random() * 2) == 0.xxxx, casting it to int results in 0
If (Math.random() * 2) == 1.xxxx, casting it to int results in 1
Hence this code prints a matrix of n * n 0 or 1 elements.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am looking for a way to divide an int into whole numbers.
What I mean by this: if I have a number 30 and I want to divide this by 4, I want the output to be 8,8,7,7.
Is there a way in Java to do this?
Thanks in advance.
Sure, Java is turing complete and therefore allows you to implement any algorithm.
I assume that the difference between the resulting numbers should be at most one - you did not explicitly write this.
Try this:
final int input = 30;
final int numberOfPieces = 4;
final int quotient = input / numberOfPieces;
final int remainder = input % numberOfPieces;
int [] results = new int[numberOfPieces];
for( int i = 0; i < numberOfPieces; i++ ) {
results[i] = i < remainder ? quotient + 1 : quotient;
}
This code first calculates the integer quotient and then equally distributes the remainder to the first "pieces".
Since you don't want equal splits of the number, what you may do is :
Divide the number by how many ever parts you want.
Round() the result
Add up the rounded of number how many ever times required & check if sum is same, if not add or subtract 1 as necessary.
Eg: N = 150 , parts = 4
=> 37.5 , Round it round(37.5) => 38
Now, 38*4 = 152 and 152-150 = 2 so subtract 2 from a number and your answer is 38, 38, 38 & 36.
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
float number = 30.0f;
float parts = 4.0f;
float val = number / parts;
val = Math.round(val);
if (val * parts == number){
System.out.println("Numbers are:");
for (int i = 0; i < parts; i++)
System.out.println(val);
}
else {
int diff = Math.round((val * parts) - number);
System.out.println("Numbers are:");
for(int i = 0;i < parts - 1; i++)
System.out.println(val);
System.out.println(val - diff);
}
}
}
Output:
Numbers are:
8.0
8.0
8.0
6.0
If you want to equally share the difference in the above case then just replace the else part with this:
else {
int diff = Math.round((val * parts) - number);
System.out.println("Numbers are:");
for (int i = 0; i < parts - diff; i++)
System.out.println(val);
for (int i = 0; i < diff; i++)
System.out.println(val - 1);
}
Your output will be:
Numbers are:
8.0
8.0
7.0
7.0
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
Just started picking up java and tried to write a simple piece of code to display an approximation of Pi based on the Gauss-Legendre algorithm; the result I get in the command line from the code below is -33.343229... which seems very odd to me. I am aware that my code is not complete as I do not have a restriction on the number of digits after the decimal point, which I was going to try and get from using BigDecimal. I don't quite understand what I am supposed to do with it though after reading the documentation!
Does anyone have any idea if there are any current mistakes I can fix and also how to implement a restriction on the number of digits after the decimal point? Thank you!
class calculatePi {
public static void main(String[] args) {
calculatePi x = new calculatePi();
double y = x.approxPi(3); //3 iterations
System.out.print(y);
}
double approxPi(int i) {
double a = 1; //The initial conditions for the iteration
double b = 1 / Math.sqrt(2);
double t = 1/4;
double p = 1;
double a1 = 0; //The internal n+1 terms for the iteration
double b1 = 0;
double t1 = 0;
double p1 = 0;
while (i > 0) {
a1 = (a + b) / 2;
b1 = Math.sqrt(a*b);
t1 = t - p*(a - a1)*(a - a1);
p1 = 2*p;
a = a1;
b = b1;
t = t1;
p = p1;
i = i - 1;
}
double applepie = ((a + b)*(a + b))/(4*t);
return applepie;
}
}
double t = 1/4; does an integer division for 1/4, which results in 0. Try 1/4.0.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I made a program to sum factorials in java like 4! + 3! + 2! + 1! = 33, but it doesn't work. Could anyone help explain why?
import javax.swing.JOptionPane;
public class fac {
public static void main(String[] args) {
int sum = 0, fact, i, j;
fact = Integer.parseInt(JOptionPane.showInputDialog("ENTER NO"));
for (i = fact; i > 1; i--) {
for (j = fact - 1; j > 0; j--)
fact = fact * j;
sum = sum + fact;
}
sum = sum + 1;
System.out.print("SUM OF FACTORIAL = "+sum);
}
}
You are repeatingly calculating factorial of fact in the outer loop. The start value of the inner loop is wrong.
But you should have found this error by yourself using a debugger.
This is where methods might come in handy. First an outer loop because you're counting down (from 4, in this example).
static final int NR = 4; //for example
static void main(String[] args) {
int total = 0;
for (int i = NR; i > 0; i--)
total += calculateFactorial(i); //i += j; is the same as i = i + j;
System.out.println("Answer: " + total);
}
Now it looks way easier, right? The code suddenly became readable. Now for calculateFactorial(int nr) all we have to do is calculate 4 * 3 * 2 * 1 (for the factorial of 4, that is):
public static int calculateFactorial(int nr) {
int factorialTotal = 1;
for (int i = nr; i > 0; i--)
factorialTotal *= i; //i *= j; is the same as i = i * j;
return factorialTotal;
}
Methods just made code easy to read and write. I'd suggest you read a book like Clean Code
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I am trying to calculate and round up with an IF statement, the code is below. The error comes on the line: if (partterms < 6)
// Setup Array List for Course CU
ArrayList<Double> coursecu = new ArrayList<Double>();
// Read inputs for Course Units and Sum the Value
System.out.println("Please enter Individual Course CU values, Q to quit:");
Scanner in2 = new Scanner(System.in);
while (in.hasNextDouble())
{
coursecu.add(in.nextDouble());
}
double sum = 0;
for(int i = 0; i < coursecu.size(); i++)
{
sum = sum + coursecu.get(i);
}
System.out.println();
System.out.println("Total Credit Units Required for Graduation");
System.out.println(sum);
// Calculate the Number of Terms to Completion
{
double fullterm = sum / planned_units; // Sets Whole Terms
double partterm = sum % planned_units; // Sets Partial Terms
}
if (partterm < 6)
{
number_terms = fullterms++;
}
else
{
number_terms = fullterms;
}
{ ←
double fullterm = sum / planned_units; // Sets Whole Terms
double partterm = sum % planned_units; // Sets Partial Terms
} ←
Remove { and } and the variables will be known outside this weird block.