I am currently writing a program that estimates Pi values using three different formulas pictured here: http://i.imgur.com/LkSdzXm.png .
This is my program so far:
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
double leibniz = 0.0; // pi value calculated from Leibniz
double counter = 0.0; // starting value
double eulerall = 0.0; // pi value calculated from Euler (all integers)
double eulerodd = 0.0; // value calculated from Euler (odds)
int terms;
bool negatives = false;
cin >> terms;
cout << fixed << setprecision(12); // set digits after decimal to 12 \
while(terms > counter){
leibniz = 4*(pow(-1, counter)) / (2*counter+1) + leibniz;
counter++;
eulerall = sqrt(6/pow(counter+1,2)) + eulerall;
counter++;
eulerodd = (sqrt(32)*pow(-1, counter)) / (2*counter + 1) + eulerodd;
counter++;
cout << terms << " " << leibniz << " " << eulerall << " " << eulerodd <<endl;
}
if (terms < 0){
if(!negatives)
negatives=true;
cout << "There were " << negatives << " negative values read" << endl;
}
return 0;
}
The sample input file that I am using is:
1
6
-5
100
-1000000
0
And the sample output for this input file is:
1 4.000000000000 2.449489742783 3.174802103936
6 2.976046176046 2.991376494748 3.141291949057
100 3.131592903559 3.132076531809 3.141592586052
When I run my program all I get as an output is:
1 4.000000000000 1.224744871392 1.131370849898.
So as you can see my first problem is that the second and third of my equations are wrong and I can't figure out why. My second problem is that the program only reads the first input value and stops there. I was hoping you guys could help me figure this out. Help is greatly appreciated.
You have three problems:
First, you do not implement the Euler formulae correctly.
π2/6 = 1/12 + 1/22 + 1/32 + ...
eulerall = sqrt(6/pow(counter+1,2)) + eulerall;
The square root of the sum is not the sum of the square roots.
π3/32 = 1/13 + 1/33 + 1/53 + ...
eulerodd = (sqrt(32)*pow(-1, counter)) / (2*counter + 1) + eulerodd;
This is just... wrong.
Second, you increment counter three times in the loop, instead of once:
while(terms > counter){
...
counter++;
...
counter++;
...
counter++;
...
}
Third, and most fundamental, you didn't follow the basic rule of software development: start small and simple, add complexity as little at a time, test at every step, and never add to code that doesn't work.
my first problem is that the second and third of my equations are
wrong and I can't figure out why
Use counter++ just once. Apart from this Leibniz looks fine.
Eulerall is not correct, you should sum all factors and then do sqrt and multiplication at the end:
eulerall = 1/pow(counter+1,2) + eulerall;
// do sqrt and multiplication at the end to get Pi
The similar thing with eulerodd: you should sum all factors and then do sqrt and multiplication at the end.
My second problem is that the program only reads the first input value
and stops there.
In fact this is your first problem. This is because you are incrementing counter multiple times:
while(terms > counter){
leibniz = 4*(pow(-1, counter)) / (2*counter+1) + leibniz;
counter++; // << increment
^^^^^^^^^^
eulerall = sqrt(6/pow(counter+1,2)) + eulerall;
counter++; // << increment
^^^^^^^^^^
eulerodd = (sqrt(32)*pow(-1, counter)) / (2*counter + 1) + eulerodd;
counter++; // << increment
^^^^^^^^^^
cout << terms << " " << leibniz << " " << eulerall << " " << eulerodd <<endl;
}
You should increment counter just once.
You're using the same counter and incrementing it after each calculation. So each technique is only accounting for every third term. You should increment counter only once, at the end of the loop.
Also note that it is generally bad form to use a floating-point value as a loop counter. It only takes on integer values in your program, so you can just make it an int. Nothing else needs to change; the math will run the same because the int will promote to a double when you combine the two in math operations.
#include<iostream>
#include<conio.h>
#include<cmath>
using namespace std;
char* main()
{
while(1)
{
int Precision;
float answer = 0;
cout<<"Enter your desired precision to find pi number : ";
cin>>Precision;
for(int i = 1;i <= Precision;++i)
{
int sign = (pow((-1),static_cast<float>(i + 1)));
answer += sign * 4 * ( 1 / float( 2 * i - 1));
}
cout<<"Your answer is equal to : "<<answer<<endl;
_getch();
_flushall();
system("cls");
}
return "That is f...";
}
Related
The assignment I've been given is asking me to find out how many trees can be put in a certain length and how much total space they'd take up including the required space between the trees. Thanks to some help I've been able to get the tree total correct, but the total space taken up is incorrect. What can I do to fix this.
input is: length = 10, TRadius = .5, ReqSpace = 3
desired output is: TreeTot = 2
Total space should be 1.57
Actual output is: TreeTot = 2 Total Space is 6.1
Here is the code I'm using.
#include <iostream>
#include <iomanip>
using namespace std;
const double PI = 3.14;
int main()
{
double length;
double TRadius;
double ReqSpace;
int TreeTot = 0;
cout << "enter length of yard: ";
cin >> length;
cout << "enter radius of a fully grown tree: ";
cin >> TRadius;
cout << "required space between fully grown trees: ";
cin >> ReqSpace;
while (length > TRadius * 2 + ReqSpace) {
TreeTot += 1;
length -= (TRadius * 2) + ReqSpace;
}
cout << "The total space taken up is ";
cout << setprecision(2) << TreeTot * TRadius * PI + ReqSpace << endl;
cout << "The total amount of trees is ";
cout << TreeTot;
return 0;
}
These two lines:
TreeTot + 1;
length - (TRadius * 2) + ReqSpace;
are valid statements, but they're just expressions. You calculate a value, but don't do anything with it. TreeTot + 1... and then what? You need to assign the calculated value to something. Presumably you're wanting to increase the TreeTot and decrease the length. Just assign the values like so:
TreeTot = TreeTot + 1;
length = length - (TRadius * 2) + ReqSpace;
Or use the shorthand for modifying and assigning the result to the same value:
TreeTot += 1;
length -= (TRadius * 2) + ReqSpace;
Your answer will probably still be wrong because the if-statement only runs once - you never tell it you want it to do the code within multiple times. If you change the if to a while then the code will loop until length is too small to satisfy the condition.
I am trying to create a program to print first 200 elements following a specific numerical series condition which is
1-1-3-6-8-8-10-20
But instead of showing, just 200 elements is showing 802. I assume is because of the code inside the for loop. I have hours thinking on how to reduce that code to the job and I cannot think anything else. I am getting frustrated and need your help.
The exercise is on the code comments
//Print the following numerical series 1-1-3-6-8-8-10-20 until 200
#include <stdafx.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int Num1=200, z = 0, x = 1, y = 1;
cout << "\n\n1,";
cout << " 1,";
for (int i = 1; i <= Num1; i++)
{
z = y + 2;
cout << " " << z << ","; //It will print 3
z = z * 2;
cout << " " << z << ",";//It will print 6
z = z + 2;
cout << " " << z << ",";//It will print 8
z = z;
cout << " " << z << ",";//It will print 8
y = z;
}
cout << "\n\n";
system("pause");
return 0;
}
You're looping 200 times, and each time you loop, you're printing out 4 different numbers. You're also printing twice at the start so thats 2 + 4 * 200 = 802, which is where your 802 number output is coming from.
I assume is because of the code inside the "for" loop but I've hours
thinking on how to reduce that code to the job and I cannot think
anything else. I'm getting frustrated and need your help.
So you basically wanna simplify your code. Which can be done by noticing the repetitions.
There you can find only two types of change in the series; either a +2 or x2 with the previous element.
In each iteration this can be achieved by:
If reminder i%4 == 1 or i%4 == 3, need an increment of 2 (assuming 1 <= i <= MAX)
If reminder i%4 == 0, nothing but a multiplication of 2.
When you do like so, you can simply neglect, printing of first two ones and other complications in the total numbers in the series.
Also not that, you are trying to get 200 terms of this series, which increases in each step very fast and exceed the maximum limit of int. Therefore, long long is needed to be used instead.
The updated code will look like this:
#include <iostream>
typedef long long int int64;
int main()
{
int size = 200;
int64 z = -1;
for (int i = 1; i <= size; i++)
{
if ((i % 4 == 1) || (i % 4 == 3)) z += 2;
else if (i % 4 == 0) z *= 2;
std::cout << z << "\n";
}
return 0;
}
See the Output here: https://www.ideone.com/JiWB8W
Im having trouble with the function taylor2 not returning a value if i input anything over 2. If I enter 0-2 it outputs the correct value but anything over 2 and I just get a flashing underscore with no data returned.
void taylor2(double x)
{
double total = 1;
int i = 0;
int count = 1;
double temp = 1;
do
{
{
if (i % 2 == 1)
{
temp = (pow(x, i * 2 + 2) / factorial(i * 2 + 2));
total += temp;
}
else {
temp = (pow(x, i * 2 + 2) / factorial(i * 2 + 2));
total -= temp;
}
}
count++;
i++;
} while (fabs(temp) >= .0001);
cout << "The last recoreded temporary value was: "<<temp << endl;
cout << "The computed value for cosine is : "<< total << endl;
cout << "It took " <<count << " values to calculate the value of the function to .0001 places"<< endl;
cout << endl;
}
I suspect that factorial is returning an int. If int is 32 bit (very common), then factorial will overflow once the argument reaches 13 (i = 5 in your case). Signed integer overflow is undefined behaviour in C++.
You could use a std::uint64_t (an unsigned 64 bit integer). This will allow you to evaluate a few larger factorials.
For more reference, see Calculating large factorials in C++
Better still, use a recurrence relation between your Taylor terms.
This is my code for finding the sum of a harmonic series of 1/n. I want it to stop when the sum is greater than or equal to 15, but the code cannot run. Can anyone let me know what I'm doing wrong? It seems to follow the correct while loop structure. Thanks!
#include <iostream>
using namespace std;
int main ()
{
int divisor = 1;
int sum = 1;
while ((sum <= 15) && (divisor >=1))
{
sum = sum + (1/divisor);
divisor++;
}
cout << "You need " << divisor << " terms to get a sum <= 15" << endl;
return 0;
}
Your loop is actually running. However, your sum variable is of type int, and so is divisor.
1 (an int) / divisor (also an int) will return 1 or 0. This is because you are doing integer division. 1/1 == 1. However, 1/2 == 0, 1/3 == 0, etc... To solve this, cast divisor to double:
(1 / (double)divisor)
So that solves the issue of that segment returning only 1 or 0. However, you will still gain a sum of 1 as sum is of type int. Attempting to assign a double to an int variable will result in a truncation, or floor rounding. Sum will add the first 1, but it will remain 1 indefinitely after that. In order to solve this, change the type of sum to double.
Your assignment of sum = 1; is a logical error. Your result will be 1 higher than it should be. Your output statement is also mistaken... It should be...
cout << "You need " << divisor << " terms to get a sum > 15" << endl;
In addition, the condition of divisor >= 1 is needless... It is always greater than or equal to one because you assign it as 1 and are incrementing... If you do want a sum that is >= 15, change the while condition to...
while (sum < 15)
Your code should look like this...
#include <iostream>
using namespace std;
int main()
{
int divisor = 1;
double sum = 0; //Changed the type to double and assigned 0 rather than 1
while (sum <= 15) //While condition shortened...
{
sum = sum + (1 / (double)divisor); //Added type cast to divisor
divisor++;
}
//cout statement adjusted...
cout << "You need " << divisor << " terms to get a sum > 15" << endl;
return 0;
}
Whilst working on a personal project of mine, I came across a need to divide two very large arbitrary numbers (each number having roughly 100 digits).
So i wrote out the very basic code for division (i.e., answer = a/b, where a and b are imputed by the user)and quickly discovered that it only has a precision of 16 digits! It may be obvious at this point that Im not a coder!
So i searched the internet and found a code that, as far as i can tell, uses the traditional method of long division by making a string(but too be honest im not sure as im quite confused by it). But upon running the code it gives out some incorrect answers and wont work at all if a>b.
Im not even sure if there's a better way to solve this problem than the method in the code below!? Maybe there's a simpler code??
So basically i need help to write a code, in C++, to divide two very large numbers.
Any help or suggestions are greatly appreciated!
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std; //avoids having to use std:: with cout/cin
int main (int argc, char **argv)
{
string dividend, divisor, difference, a, b, s, tempstring = ""; // a and b used to store dividend and divisor.
int quotient, inta, intb, diff, tempint = 0;
char d;
quotient = 0;
cout << "Enter the dividend? "; //larger number (on top)
cin >> a;
cout << "Enter the divisor? "; //smaller number (on bottom)
cin >> b;
//making the strings the same length by adding 0's to the beggining of string.
while (a.length() < b.length()) a = '0'+a; // a has less digits than b add 0's
while (b.length() < a.length()) b = '0'+b; // b has less digits than a add 0's
inta = a[0]-'0'; // getting first digit in both strings
intb = b[0]-'0';
//if a<b print remainder out (a) and return 0
if (inta < intb)
{
cout << "Quotient: 0 " << endl << "Remainder: " << a << endl;
}
else
{
a = '0'+a;
b = '0'+b;
diff = intb;
//s = b;
// while ( s >= b )
do
{
for (int i = a.length()-1; i>=0; i--) // do subtraction until end of string
{
inta = a[i]-'0'; // converting ascii to int, used for munipulation
intb = b[i]-'0';
if (inta < intb) // borrow if needed
{
a[i-1]--; //borrow from next digit
a[i] += 10;
}
diff = a[i] - b[i];
char d = diff+'0';
s = d + s; //this + is appending two strings, not performing addition.
}
quotient++;
a = s;
// strcpy (a, s);
}
while (s >= b); // fails after dividing 3 x's
cout << "s string: " << s << endl;
cout << "a string: " << a << endl;
cout << "Quotient: " << quotient << endl;
//cout << "Remainder: " << s << endl;
}
system ("pause");
return 0;
cin.get(); // allows the user to enter variable without instantly ending the program
cin.get(); // allows the user to enter variable without instantly ending the program
}
There are much better methods than that. This subtractive method is arbitrarily slow for large dividends and small divisors. The canonical method is given as Algorithm D in Knuth, D.E., The Art of Computer Programming, volume 2, but I'm sure you will find it online. I'd be astonished if it wasn't in Wikipedia somewhere.