I am a complete beginner in programming and I was given the following assignment:
Write a C++ program that computes a pair of estimates of π, using a sequence of inscribed and circumscribed regular polygons. Halt after no more than 30 steps, or when the difference between the perimeters of the circumscribed and inscribed polygons is less than a tolerance of ε=10⁻¹⁵. Your output should have three columns, for the number of sides, the perimeter of an inscribed polygon, and perimeter of the circumscribed polygon. For the last two columns, display 14 digits after the decimal point.
well, I decided to use the law of cos to find the lengths of the sides of the polygon but when I was testing out my program I realized the line:
a = cos(360 / ngon);
keeps giving me a zero as the output which makes everything else also zero and I am not sure what is wrong please help.
P.S. Sorry if the program looks really sloppy, I am really bad at this.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#define _USE_MATH_DEFINES
#include <math.h>
#include <cmath>
using namespace std;
int main()
{
char zzz;
int ngon = 3, a, ak;
double insngon = 0.0;
double cirngon = 0.0;
cout << "Number of Sides" << "\t\t\t" << "Perimeter of insribed region" << "\t\t\t" << "Perimeneter of circumscribed polygon" << "\t\t" << "\n";
while (ngon <= 30)
{
a = cos(360 / ngon);
ak = pow(.5, 2) + pow(.5, 2) - 2 * .5*.5*a;
insngon = (ak*ngon);
cirngon = (ak / (sqrt(1 - pow(ak, 2))));
cout << fixed << setprecision(14) << ngon << " " << insngon << " " << cirngon << endl;
ngon++;
if (cirngon - insngon <= pow(10.0, -15));
cin >> zzz;
return 0;
}
cout << "\nEnter any character and space to end ";
cin >> zzz;
return 0;
}
One issue is that you declared integers, yet you are using them in the call to cos here:
int ngon = 3, a, ak;
//...
a = cos(360 / ngon);
Since a is an integer, the return value of cos (which is of type double) will be truncated. Also, since ngon is an integer, the 360 / ngon will also truncate.
The fix is to make a a double, and divide 360.0 by ngon to prevent the truncation:
int ngon = 3, ak;
double a;
//...
a = cos(360.0 / ngon);
The other issue, as pointed out in the comments is that the trigonometric functions in C++ use radians as the argument, not degrees. You need to change the argument to the equivalent value in radians.
Another issue is that you're using pow to compute values that are constant. There is no need to introduce an unnecessary function call to compute constant values. Just define the constants and use them.
For example:
const double HALF_SQUARED = 0.25
const double EPSILON_VALUE = 10.0e-15;
and then use HALF_SQUARED and EPSILON_VALUE instead of the calls to pow.
Also, pow is itself a floating point function, thus can produce results that are not exact as is discussed by this question . Thus pow(ak, 2) should be replaced with simply ak * ak.
Use float a; (or double a) instead of int a.
Here the return type of a is int
And calculating
a = cos(360/ngon)
Is equivalent to a= cos(120) that is the result of cos(120) is 0.8141 and being a integer type "a" will only store the integer part it.
Therefore 'a' will be 0 and discarding floating value.
Also use double ak; instead of int ak;.
Because here pow function has been used which have return type 'double'
Related
I need to make a code for the Viete's formula for pi for my extended essay. In the code i have the individual terms, but I don't know how to combine them all and use the product function to get the product of all the terms.
This is what i have till now:
#include <stdio.h>
#include <math.h>
int main()
{
int n, i;
n = 10;
i = 1;
double an = sqrt(2);
while(i <= n)
{
printf("a%d = %.10f\n", i, an);
an = sqrt(2 + an);
++i;
}
return 0;
}
Although you've tagged C++, the code you present is strictly old-school C. I'll skip the mini-code review I usually do as you presented a bunch of variable declarations and nothing more.
Here's a program that utilizes both the "product formula" and limit expression. Both expressions are products, so that's where the confusion came from. However, it helps to read up on the stuff you're intending to work with.
// Someone who knows ranges better than me might be able to shorten this up.
#include <cmath> // Preferred over <math.h> when writing C++
#include <iomanip>
#include <iostream>
#include <numbers> // inv_pi and sqrt(2) as of C++20
// Note the lack of a sqrt() function call or use of std::numbers::sqrt2
double viete_product(int n) {
double product = 1.0;
for (int i = 1; i <= n; ++i) {
product *= std::cos(std::numbers::pi / std::pow(2.0, i + 1));
}
return product;
}
// The limit expression does require a sqrt(2) as an initial term.
// Both are product formulas, which likely is the cause of confusion.
double viete_limit_expression(int n) {
/*
* I'm not in the business of doing people's homeowork for them
* so I'm excluding the code I assume you have to implement.
* The other product formula provides enough of a foundation
* that you should be able to figure it out from there.
*/
}
int main() {
const int numRounds = 10;
std::cout << std::setw(25) << std::right
<< "2 / pi : " << (2.0 * std::numbers::inv_pi) << "\n"
<< std::setw(25) << std::right
<< "Viete product: " << viete_product(numRounds) << "\n"
<< std::setw(25) << std::right
<< "Viete limit expression: " << viete_limit_expression(numRounds)
<< '\n';
}
Output:
❯ ./a.out
2 / pi : 0.63662
Viete product: 0.63662
Viete limit expression: 0.63662
At this precision, 10 rounds gets a convergence. I didn't try to find out what a minimum number of rounds was at this precision, 10 or a 100 rounds ran essentially the same on my machine.
As far your code is concerned, you have the setup. You just need to do the math. It's a division and a multiplication in a loop. Write out how you would hand calculate the answer, and the adapt that algorithm to code.
Given the posted code, it seems that the OP is trying to calculate π using the Viète's formula in the form of infinite product of nested radicals.
I'd start rearrenging that formula to make the intent more explicit.
I have the individual terms, but I don't know how to combine them all and use the product function to get the product of all the terms.
I assume that by "product function" the OP means the product of a sequence of factors.
The easiest way to translate that in C++ is to write a simple loop.
double product = starting_value; // Hopefully not 0.
for ( int i = 1; i <= n; ++i ) {
// Evaluate the factor somehow...
product *= factor_i; // product = product * factor_i
}
The OP already figured out the following recurrence relation.
The missing piece is the sequence of products.
Given that this is a converging sequence and that a double has only a limited precision, you may consider to stop the iterations when a certain accuracy has been reached, instead of relying on a fixed number of iterations.
Moreover, at some point (after 26 iterations, in my experiments) the numeric value of the product won't change anymore.
I'm beginner in using functions, and I wrote this simple code. But I don't know why the volume is always calculated as zero.
#include <iostream>
using namespace std;
double area (double) ;
double volume (double) ;
int main () {
double radious ;
cout << "please enter the Radious \n" ;
cin >> radious ;
cout << "The area = " << area(radious) << "\n" ;
cin >> radious ;
cout << "The volume = " << volume(radious) << "\n" ;
cout << radious << "\n" ;
}
// defintion function of the area
double area (double R) {
return ( (4) * (3.14) * (R * R) ) ;
}
// defintion function of the volume
double volume (double R) {
return ( (3/4) * (3.14) * (R * R * R) ) ;
}
Your function volume will always return zero because 3 divided by 4 is 0 when interpreted as an integer. This is because casting any real value to integer will simply result in discarding decimal part. For example, 2.7 as int will be 2 not 3, there is no rounding, in a mathematical sense.
You can fix this in 2 ways:
A) reorder your equation so division will be the last operation you do, e.g. ((3.14*R*R*R*3)/4). Note that this is often necessary, when you want your result to be int, which is not the case here.
B) explicitly say that either (or both) 3 or 4 have to be treated as a real number (float/double) by adding .0, e.g. 3.0/4 or 3/4.0 or 3.0/4.0. This approach is better in your case since you expect double anyway.
For more information refer to Numeric conversions and this FAQ
The part 3/4 in your code performs an integer division. Integers cannot have floating points so usually the last part of integer is truncated, which leaves 0 in your case.
You can replace 3/4 with 3.0/4.0to make it work.
Good Luck!
I'm trying to make a program that uses the Taylor Sequence to approximate e.
However, I've come across a problem that makes me feel quite noobish at C++. the variable e is a float, but whenever I use cout << e << "\n"; it just outputs 2, not 2.0 or 2.7 or whatever it should be outputting at any point in the code. Here's the main() code:
int main() {
float e = 1.0;
int d = 1;
int counter = 25;
while(counter>=1){
counter-=1;
e+=(1/fact(d));
d++;
cout << e << "\n";
}
}
fact() computes the factorial (!) of a number. When I run the program I get 25 lines that say 2. What am I doing wrong? And I do have #include <iostream> and using namespace std; before the functions.
Your division returns an integer and not actually a float. One of the sides of the division has to be a float for the output to be a float.
Changing:
e+=(1/fact(d));
to:
e += (1.0 / fact(d));
Should solve your problem.
//findSlope(twoPoints).exe
//finding the slope of line AB, using coordiantes of point A and B.
#include <iostream>
int main()
{
int a, b, c, d;
float answer;
std::cout << "The X coordiante of A: ";
std::cin >> a;
std::cout << "\nThe Y coordiante of A: ";
std::cin >> b;
std::cout << "\nThe X coordiante of B: ";
std::cin >> c;
std::cout << "\nThe Y coordiante of B: ";
std::cin >> d;
std::cout << "\nThe slope of line AB = " << std::endl;
answer = (b-d)/(a-c);
std::cout.setf(std::ios::fixed);
std::cout.precision(3);
std::cout << answer << std::endl;
//alternative= std::cout << fixed << setprecision(#) << answer << std::endl;
std::cout.unsetf(std::ios::fixed);
return 0;
}
I am learning C++ and I tried to code a program that calculate the slope using the coordinates of two points.
I understand that if I use float for variables I declared for the coordinates, the result of the calculation would output as float with decimals. However, I wonder if I may still use int for user input so that I can ensure the inputs are integers.
Extra question: Would it be possible to convert a float presented in the form of "#.##" to "# #/#"? More like how we do mathematics IRL.
You can use implicit conversion to double:
answer = (b-d)/(a-c*1.0);
Or explicit cast:
answer = (b-d)/(a-(float)c);
Bonuses:
for the fraction part: Converting decimal to fraction c++
Why does integer division result in an integer?
You can use int for user input, but to precisely calculate anything that contains a division operator /, you'll need to cast to floating point types.
It's usually considered a good practice in C++ to use static_cast for that (although you still may use c-style (float) syntax).
For example:
answer = static_cast<float>(b - d) / (a - c);
Here, you convert (b - d) to float and then divide it by integer, which results in a float.
Note that the following wouldn't work correctly:
answer = static_cast<float>((b - d) / (a - c));
The reason is that you first divide an int by another int and then convert the resulting int to a float.
P. S. float is really inaccurate, so I would advise to use double instead of float in all cases except where you want to write faster code that does not depend on mathematical accuracy (even though I'm not sure it would be faster on modern processors) or maintain compatibility with an existing library that uses float for some of its functions.
My goal is to add the value in front of my decimal place when the first decimal places is more than or equal to 5.
For example:
#include <iostream>
using namespace std;
int main()
{
float num = 0.5222f;
cout << (int)num << endl;
cin.get();
return 0;
}
My intended result is 1 instead of 0. How should I modify the code to get the expected result?
If you want to round this value to the nearest integer, you could just add 0.5 before casting it to int:
float num = 0.5222f;
cout << (int)(num + 0.5);
or alternatively you might use one of the following functions from the <cmath> header:
double round (double x);
float roundf (float x);
long double roundl (long double x);
In C++11 we now have std::round, so this would work fine:
std::cout << std::round(num) << std::endl;
would also need to include <cmath>. The non-C++11 method using floor:
std::cout << floor(num + 0.5) << std::endl;
If you cast a float to an int it rounds towards zero, dropping the fractional portion of the number.
What you want to do is call roundf first. (round for double, roundf for float)
cout << (int)roundf(num) << endl;
I just add:
float num = 0.5222f;
cout << std::floor(num + 0.5);
In this way you can even decide to round up also if (say) first digit is > 3
float num = 0.3222f;
cout << std::floor(num + 0.7);
Don't know how much useful, but.... you can!
Try the ceil function.
It rounds up numbers of 0.5 to a whole decimal number by 1.
http://en.cppreference.com/w/cpp/numeric/math/ceil