I'm building a simple class in Java that is used in order to calculate the value of Pi, and print the real value of Pi at it's side.
The program's input is a string of a natural number (bigger than 0) which is used to determine the precision of the calculation.
This is my code:
public class Pi {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
double myPi = 0;
for (int i=0 ; i<N ; i++) {
myPi += (Math.pow(-1,i))*(1/((i*2)+1));
}
myPi *= 4;
System.out.println(myPi + " " + Math.PI);
}
(*there's missing closing brackets only here in the text for some reason)
The problem is that the variable "myPi" only changes for the first iteration of the for loop.
For example, for the input 4 (N=4) the result will be 4.0 instead of 3.1....
Couldn't find a solution for this one, thanks!
(1/((i*2)+1))
the above expression is evaluated to 0 in every case except for i == 0 as it is an integer division and the expected value is a fraction which evaluates to 0
You need to use floating point arithmetic in order to get a float value.
(1.0/((i*2)+1)) <-- Note the 1.0 here
if you want to a double value as a result an operation, at least one operand must be double.
try this
int N = Integer.parseInt(args[0]);
double myPi = 0;
for (int i=0 ; i<N ; i++) {
myPi += (Math.pow(-1,i))*(1.0/((i*2)+1));
}
myPi *= 4;
System.out.println(myPi + " " + Math.PI);
Related
I am doing an assignment where I must use nested loops in order to add up the squares and cubes of integers from 1 to N (N being whatever the user inputs). For example, if the user input the number 5, the program is supposed to do "1²+2²+3²+4²+5²" and output the sum of those numbers, as well "1³+2³+3³+4³+5³" and output the sum of those numbers.
However, I am having trouble figuring out how to code it in a way that I receive the proper output? This is what I wrote. Scanners were already added.
int limitNum = input.nextInt();
double squareNums:
double sumofSq = 0;
double cubedNums;
double sumofCubes = 0;
for(int s = 1; s <= limitNum; s++)
{
for(int c = 1; c <= limitNum; c++)
{
cubedNums = Math.pow(c, 3);
sumofCubes = sumofCubes + cubedNums;
}
squareNums= Math.pow(s, 2);
sumofSq = sumofSq + squareNums;
}
But currently, when I run this program, the sum of the squares output correctly, but the sum of the cubes is always some big number. For example if 5 is used, sumofSq would output 55.0, but sumofCubes would output 1125.0.
There is no point using a nested loop as this would result in complexity of O(n²). A single loop would be sufficient and be in complexity class O(n).
public class Application {
public static void main(String[] args) {
var squareSum = 0d;
var cubeSum = 0d;
var upperBound = 5;
for(var i = 1; i <= upperBound; i++){
squareSum += Math.pow(i, 2);
cubeSum += Math.pow(i, 3);
}
System.out.printf("""
Sum of first n squares: %s
Sum of first n cubes: %s
""", (int)squareSum, (int)cubeSum);
}
}
In fact there is no need to loop at all => constant computation time no matter the size of the input O(1). There is a well known formula which tells you the sum of the first n squares.
n(n+1)(2n+1)
------------
6
Please see this for a proof.
The same holds true for the first n cubes.
n²(n+1)²
--------
4
Please see this for a proof.
The following program will therefore return the same result.
public class Application {
public static void main(String[] args) {
var upperBound = 5;
System.out.printf("""
Sum of first n squares: %s
Sum of first n cubes: %s
""", sumOfFirstNSquares(upperBound), sumOfFirstNCubes(upperBound));
}
public static int sumOfFirstNSquares(int n){
return (n * (n+1) * (2 * n + 1)) / 6;
}
public static int sumOfFirstNCubes(int n){
return ((n * n) * (n+1) * (n+1)) / 4;
}
}
In fact there is no need to loop at all => constant computation time no matter the size of the input O(1). There is a well known formula which tells you the sum of the first n squares.
java
e can be approximated using the formula e = 1 + (1/1!) + (1/2!) + (1/3!)... + (1/n!). I am trying to use for loops to accept whatever integer the user sets n to be. The program should approximate e by using the formula above from (1/1!) + .... (1/n!) and out put the result.
The nested for loop calculates the factorial of n (tested it separately and it works) and the variable defined, frac, puts the factorial into a fraction of 1/(answer to factorial). I store the value into a variable e and it should add the new fraction to the old value every time an iteration is done. I cannot not understand what is wrong with my loops that they are not out putting the right answer.
System.out.println("Enter an integer to show the result of
approximating e using n number of terms.");
int n=scan.nextInt();
double e=1;
double result=1;
for(int i=1; n>=i; n=(n-1))
{
for(int l=1; l<=n; l++)
{
result=result*l;
}
double frac=(1/result);
e=e+frac;
}
System.out.println(e);
Output when I enter the integer 7 as n = 1.0001986906956286
You don't need that whole inner loop. All you need is result *= i.
for (int i = 1; i <= n; i++)
{
result *= i;
double frac = (1 / result);
e += frac;
}
Here's a JavaScript version I just threw together:
function init() {
const elem = document.getElementById('eapprox');
let eapprox = 1;
const n = 15;
let frac = 1;
for (var i = 1; i <= n; ++i) {
frac /= i;
eapprox += frac;
}
elem.textContent = eapprox;
}
This yields 2.718281828458995. Plunker here: http://plnkr.co/edit/OgXbr36dKce21urHH1Ge?p=preview
This is the formula that can be used to calculate the square root of a number.
result=(guess+(number/guess))/2;
For example, I need to get the square root of 9. First, I need to make a guess. For this one, it's 6. Although, I know that the square root of 9 is 3, I chose 6 to show how the program should work.
that makes...
result=(6+(9/6))/2 which is equal to 3.75.
To get the actual square root of 9, I need to make the result the new guess.The program should continue as...
result=(3.75+(9/3.75))/2 which is equal to 3.075.
This process should continue till difference between result and the result after it is equal to 0. For example
result=(3+(9/3))/2 is always equal to 3.
When the value of result is passed to guess, the next result will also be 3. That means 3 is the square root of nine.
Here's my code:
package javaPackage;
public class SquareRoot {
public static void main(String[] args) {
calcRoot();
}
public static void calcRoot(){
double num=9;
double guess=6;
double result=0;
while(Math.abs(guess-ans)!=0){
result=(guess+(num/guess))/2;
guess=result;
}
System.out.print(result);
}
}
Output
3.75
My problem is I can't compare the value of result and the previous result. Since guess is equal to result, the program immediately since guess and result are already equal. How can I fix it?
Just exchange the two statements in the while loop (and the initializations to avoid a division by zero):
public static void calcRoot(){
double num=9;
double guess=0;
double result=6;
while(Math.abs(guess-result)!=0){
guess=result;
result=(guess+(num/guess))/2;
}
System.out.print(result);
}
The trick is to have the old value still in guess and the new one in result when the test is executed.
And you should not test for != 0, due to rounding errors this may not be achieved. Better test for some small value >= 1e-7
To compare the result with the previous result you need to keep both of them in a variable.
This does a binary chop.
public static double sqrt(double ans) {
if (ans < 1)
return 1.0 / sqrt(1.0 / ans);
double guess = 1;
double add = ans / 2;
while (add >= Math.ulp(guess)) {
double guess2 = guess + add;
double result = guess2 * guess2;
if (result < ans)
guess = guess2;
else if (result == ans)
return guess2;
add /= 2;
}
return guess;
}
public static void main(String[] args) {
for (int i = 0; i <= 10; i++)
System.out.println(sqrt(i) + " vs " + Math.sqrt(i));
}
prints
0.0 vs 0.0
1.0 vs 1.0
1.414213562373095 vs 1.4142135623730951
1.7320508075688772 vs 1.7320508075688772
2.0 vs 2.0
2.236067977499789 vs 2.23606797749979
2.449489742783178 vs 2.449489742783178
2.64575131106459 vs 2.6457513110645907
2.82842712474619 vs 2.8284271247461903
3.0 vs 3.0
3.162277660168379 vs 3.1622776601683795
and
for (int i = 0; i <= 10; i++)
System.out.println(i / 10.0 + ": " + sqrt(i / 10.0) + " vs " + Math.sqrt(i / 10.0));
prints
0.0: 0.0 vs 0.0
0.1: 0.31622776601683794 vs 0.31622776601683794
0.2: 0.4472135954999581 vs 0.4472135954999579
0.3: 0.5477225575051662 vs 0.5477225575051661
0.4: 0.6324555320336759 vs 0.6324555320336759
0.5: 0.7071067811865476 vs 0.7071067811865476
0.6: 0.7745966692414834 vs 0.7745966692414834
0.7: 0.8366600265340758 vs 0.8366600265340756
0.8: 0.894427190999916 vs 0.8944271909999159
0.9: 0.9486832980505138 vs 0.9486832980505138
1.0: 1.0 vs 1.0
Just create another variable to store the value of the previous guess.
This is the code:
package javaPackage;
public class SquareRoot {
public static void main(String[] args) {
calcRoot();
}
public static void calcRoot(){
double num=9;
double guess=6;
double prevGuess=0;
double result=0;
while(Math.abs(guess-prevGuess)!=0){
result=(guess+(num/guess))/2;
prevGuess = guess;
guess=result;
}
System.out.print(result);
}
}
For performance,following this code:
public static double sqrt(double num) {
double half = 0.5 * num;
long bit = Double.doubleToLongBits(num);
bit = 0x5fe6ec85e7de30daL - (bit >> 1);
num = Double.longBitsToDouble(bit);
for (int index = 0; index < 4; index++) {
num = num * (1.5f - half * num * num);
}
return 1 / num;
}
About the magic number 0x5fe6ec85e7de30daL,you can see the FAST INVERSE SQUARE ROOT
Let's see the performance,the test code:
double test = 123456;
//trigger the jit compiler
for (int index = 0; index < 100000000; index++) {
sqrt(test);
}
for (int index = 0; index < 100000000; index++) {
Math.sqrt(test);
}
//performance
long start = System.currentTimeMillis();
for (long index = 0; index < 10000000000L; index++) {
sqrt(test);
}
System.out.println("this:"+(System.currentTimeMillis() - start));
start = System.currentTimeMillis();
for (long index = 0; index < 10000000000L; index++) {
Math.sqrt(test);
}
System.out.println("system:"+(System.currentTimeMillis() - start));
System.out.println(sqrt(test));
System.out.println(Math.sqrt(test));
and the result is:
this:3327
system:3236
this result:351.363060095964
system result:351.363060095964
public static double sqrt(double number)
{
double dd=number, sqi, sqrt=0;
long i, b=0, e=0, c=1, z, d=(long)number, r=0, j;
for (i=1l, sqi=1; ; i*=100l, sqi*=10)
{
if (i>dd)
{
i/=100;
sqi/=10;
j=i;
break;
}
}
for (z=0l; z<16; dd=(dd-(double)(r*i))*100, j/=100l, sqi/=10, z++)
{
r=(long)(dd/i);
d=(e*100l)+r;
int a=9;
for (c=((b*10l)+a)*a; ; a--)
{
c=((b*10l)+a)*a;
if (c<=d)
break;
}
//if (a>=0)
// System.out.print(a);
e=d-c;
sqrt+=a*sqi;
if (number==sqrt*sqrt && j==1)
break;
//if (j==1)
// System.out.print('.');
b=b*10l+2l*(a);
}
return sqrt;
}
Sorry for the undefined variable names....but this program really works!
This program is based on long division method of finding square root
I tried to do it but i'm getting 1.0 as answer every time i run it. I'm not being able to find out what's wrong please help me. Here are the codes:
import java.util.Scanner;
public class Number23 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n=0;
float sum = 0,r = 0;
System.out.print("Enter a number for n: ");
n = input.nextInt();
for(int x = 1; x <= n; x++)
{
r = (1/x);
sum = sum + r;
}
System.out.print("The sum is "+sum);
}
}
In order to produce a reciprocal that has a floating point value it is not enough to declare r a float: the expression you assign it needs to be float as well. You can do it by using the f suffix on the constant 1 which you divide by x:
r = (1f / x);
Without the suffix, your expression represents an integer division, which produces an integer result, and drops the fraction. In your case, the only time that you get a value other than zero is when x is equal to 1.
class reciprocal
{
public static void main ( int n)
{
float i,a,s=0;
for(i=1;i<=n;i++)
{
a= 1/i;
s+=a;
}
System.out.print( "sum is "+s);
}
}
Should I point out that I am a begginer at this?
double averageMonthlyTemp() {
double[] amt = new double[52];
int sum = 0;
int index = 0;
for (int i = 0; i < temp.length - 1; i = i + 7) {
//where temp is an existiing
//previously initialized array
//of 365 elements, form 0 to 364
for (int j = 0; j < 7; j++) {
sum = sum + temp[i + j];
if (j % 7 == 6) {
double average = ((double) sum) / 7;
amt[index] = average;
index++;
sum = (int) 0;
}
}
}
return amt;
}
When I try to compile, I get an "incompatible types" error, with the "amt" at return amt marked in red. Does somebody know why?
Your method averageMonthlyTemp is specified to return some value of type double, but your amt variable is actually a double[]. Either make averageMonthlyTmp return an array of doubles, or do something like this:
double averageMonthlyTmp(int month) {
...
return tmp[month]; // could be made more efficient by only calculating the temperature for one month
}
A couple of additional notes about the code:
Because j goes from 0 to 6 inclusive, the if (j % 7 == 6) can be replaced with if (j == 6). Also, it looks like that code (computing the average) can go directly after the second for loop.
In your first for loop, the code will be cleaner if you replace i = i + 7 with i += 7, which will also increase i by 7 each time.
You don't need to put (int) before the 0 in the line sum = (int) 0;, because Java knows that when you just write 0, you mean an int.
your method definition for averageMonthlyTemp says that it is supposed to return a double, that is a single value of datatype double but you are returning amt which is a double array, that is why the compiler complains. So you can either change the method definition to return an array or return a single value.
the returned value amt is double[]. But the function returns only a double value (not an array of double ). so try to rename the function as
double [] averagemonthlytemp()
{
}