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.
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 have implemented a program in C++ and it showed a very strange bug.
First of all, if I assigned my variable a like this: long long a = 1e9 + 10 and then print the value of a, it ran correctly. But if I set a to 1e18 + 10 and then print the value of a, it showed that a equals 10^18 only. Can anyone help me with this? I tried a lot but I can't understand why. Thanks.
This is my code:
#include <iostream>
using namespace std;
int main() {
long long a = 1e9 + 10;
cout << a << endl;
a = 1e18 + 10;
cout << a << endl;
return 0;
}
1e18 is a value having type double. The presicion of type double is typically around 15 decimal digits, so adding 10 to 1e18 may not change the value of double.
You can add a cast to long long before addition to eliminate the issue in this case, but generally you should avoid using floating-point numbers to deal with integers.
#include <iostream>
int main(void) {
long long value = static_cast<long long>(1e18) + 10;
std::cout << value << '\n';
return 0;
}
my goal is to turn a double's fraction part into an integer, for example: turn 0.854 into 854 or turn 0.9321 into 9321 (the whole part of the double is always 0)
i was doing it like this, but i dont know how to fill the while's parameters to make it stop when variable x becomes a whole number without a fraction:
double x;
cin >> x;
while(WHAT DO I TYPE HERE TO MAKE IT STOP WHEN X BECOMES A WHOLE NUMBER){
x *= 10;
}
it would be best if i could do it with a loop, but if it is not possible, i am open to other suggestions :)
That question has no answer in a mathematical/logical sense. You have to read how floating point numbers in computers work, see e.g.
https://en.wikipedia.org/wiki/Floating-point_arithmetic
and understand that they are not decimal point numbers in memory. A floating point number in memory consists of three actual numbers: significant * base^{exponent} and according to IEEE the base used is "2" in basically any modern floating point data, but in even more generality, the base can be anything. Thus, whatever you have in your mind, or even see on your screen as output, is a misleading representation of the data in memory. Your question is, thus, mainly a misconception of how floating point numbers in computers work...
Thus, what you specifically ask for does in general not exist and cannot be done.
However, there may be special application for output formatting or whatever where something like this may make sense -- but then the specific goal must be clearly stated in the question here. And in some of such cases, using a "string-based" approach, as you suggested, will work. But this is not an answer to your generic question and has the high potential to also mislead others in the future.
Actually, one way to make your question obvious and clear is to also specify a fixed desired precision, thus, numbers after the decimal point. Then the answer is quite trivially and correctly:
long int value = fraction * pow(10, precision);
In this scenario you know 100% what your are doing. And if you really like you could subsequently remove zeros from the right side...
int nTrailingZeros = 0;
while (value%10 == 0) {
value /= 10;
++nTrailingZeros;
}
However there is another principle problem on a numerical level: there is no mathematical difference between, e.g., 000003 and just 3, thus in any such application the input 0.000003 will give the same results as 0.0003 or 0.3 etc. This cannot be a desired functionality... it is pretty useless to ask about the *value of the fractional part of a floating point number. But, since we have a known precision`, we can do:
cout << setw(precision-ntrailing) << setfill('0') << value << endl;
which will fill in the eventually missing leading zeros.
See this complete tested test code
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
double v = 0.0454243252;
int precision = 14;
long int value = v*pow(10,precision);
cout << value << endl;
// 4542432520000
int nTrailingZeros = 0;
while (value%10 == 0) {
value /= 10;
++nTrailingZeros;
}
cout << value << endl;
// 454243252
cout << setw(precision-ntrailing) << setfill('0') << value << endl;
// 0454243252
}
Here is a possible approach:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
int main()
{
cout << "Enter Number: ";
double user_input;
cin >> user_input;
int user_input_to_int = int(user_input);
double decimal_value = user_input - user_input_to_int;
ostringstream oss;
oss << std::noshowpoint << decimal_value;
string num_str = oss.str();
int str_length = num_str.size()-2;
int multiplier = 1;
for (int x = 0; x < str_length; x++)
{
multiplier *= 10;
}
cout << "\n";
cout << "Whole number: " << user_input_to_int << endl;
cout << "Decimal value: " << decimal_value*multiplier << endl;
}
Compare the difference between double and integer part. It is working only if x is less than 2^63.
while (x - long long(x) > 0)
find 2 real numbers find the fractional part smaller than these numbers
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'
This question already has answers here:
Why does division result in zero instead of a decimal?
(5 answers)
Closed 8 years ago.
So i am trying to make one of my first very simple math programs in c++. the problem is that
i can't seem to get the function potodds to do what i want. There is no problem in getting it to multiple the two variables (x,y) that works perfectly fine. the problem occurs when i try to replace return x*y*100 with return (x/y)*100. in this case it always return the value 0?
Hopes that someone out there can help me pinpoint my mistake.
The code looks like this:
#include "stdafx.h"
#include <iostream>
int x;
int y;
int potodds(int x, int y) {
return x * y * 100; //(x/y)*100;
}
int main() {
using namespace std;
cout << "what's the size of the pot?" << endl;
cin >> y;
cout << "what's the size of the bet?" << endl;
cin >> x;
cout << "your potodds are:" << endl;
cout << potodds(x, y) << endl;
return 0;
}
Thanks to Ebyrob i got the solution.
the problem that I was having was that I was trying to divide an integer, that was assigned a decimal value and by definition an integer can only contain whole numbers. The result was that the integer was rounded down to zero.
x and y are defined as integral values. The integral division returns only the quotient. So if x is less than y then x /y will be equal to 0.
So it would be better to substitute expression ( x /y ) * 100 for ( 100 * x ) / y
Otherwise use float numbers
For example
( double )x / y * 100
Changing int to double should solve the problem but also "using namespace std;" is always outside of main when I program. I don't know if this affects anything but you might consider putting it above your main function because it might be causing a problem now or it might cause a problem in another program you make. I think it is a matter of it being global or private but I would have it outside of main so that any other functions you use can use it ( assuming I'm right ).
If you divide two integers, the result will be an integer (the quotient: the remainder is discarded).
So, 1 / 2 -> 0 instead of 0.5.
Note also that (1 / 2) * 100 is therefore 0 * 100 -> 0, while, as Vlad says,
100*1/2 -> 100/2 -> 50, which is what you want.