I'm trying to work out the arctan of a number using the formula:
arctan(x) = x - x^3/3 + x^5/5 - x^7/7...
I have to calculate it to 20 decimal places. The answer should be 0.78539....
This is the code I have written, including some debugging statements. The problem is in the calculation I think but I just can't see it. Could someone point me in the right direction please?
EDIT : Can't use the atan function, has to be manually calculated using a double variable from user input.
#include <iomanip>
#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;
int main(void)
{
double x;
int i;
int j;
int y=3;
cout<<"Please enter the number you wish to calculate the arctan of:"<<endl;
cin>>x;
//Calculate arctan of this number
cout<<x;
cout<<"\n";
cout<<y;
cout<<"\n";
cout<<"Start\n";
x=x-(pow(x,y)/y);
y=y+2;
cout << setprecision (20) << x;
cout<<"=x before loop\n";
cout<<y;
cout<<"=y before loop\n";
for(i=0;i<9;i++)
{
x=x+(pow(x,y)/y);
cout<<x;
cout<<"=x1 in loop\n";
y=y+2;
cout<<y;
cout<<"=y1 in loop\n";
x-(pow(x,y)/y);
cout<<x;
cout<<"=x2 in loop\n";
y=y+2;
cout<<y;
cout<<"=y2 in loop\n";
}
return 0;
}
Well, your x is changing! You probably want to use a different variable to store the value computed so far and the argument to your function. That said, don't expect to precise outputs because all those computations involve rounding.
This line:
x-(pow(x,y)/y);
might have something to do with your problem.
I would strong advise you use the inbuilt atan function, it is more than likely been well optimised for you architecture, as well as being a standard function recognised by most C++ programmers.
#include <cmath>
#include <iostream>
int main()
{
double d;
std::cout << "enter number" << std::endl;
std::cin >> d;
std::cout << "atan of: " << d
<< " is " << std::atan(d)
<< std::endl;
return 0;
}
I agree with #Mystical. I don't think you're going to get 20 digits of precision out of a double. I think you need a long double (if that exists on your system) or, perhaps you need to implement your own big-num class...
Related
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
This question already has answers here:
Printing the correct number of decimal points with cout
(13 answers)
Closed 1 year ago.
As a newbie in the world of programming, I have to write a bit of C++ code to find the average of two numbers.
However, my code somehow appears to be incorrect. Please take a look at my code:
#include <iostream>
using namespace std;
int main() {
float a, b, average;
cin >> a;
cin >> b;
average = (a+b)/2;
cout << average << endl;
}
however, it says I am wrong because when I input 10 10 it outputs 10 but the system wants me to output 10.00
You need to use some I/O manipulators.
std::setprecision and std::fixed
Example:
#include <iomanip>
#include <iostream>
int main() {
if(float a, b; std::cin >> a >> b) {
float average = (a+b)/2;
std::cout << std::fixed << std::setprecision(2) << average << '\n';
}
}
Like others have said you need to change your cout line to:
cout << fixed << setprecision(2) << average << endl;
Remember that with the <<s you're putting a stream of data (an iostream) into cout. The first piece of data is std::fixed which says "Display floats to a fixed number of decimal places, don't cut off any trailing zeros." And then std::setprecision(2) says "Make that fixed number of decimal places 2." You could use an int variable or another number in place of 2 if you wanted. From there the stream has your average and an endline like before.
Set decimal precision
Sets the decimal precision to be used to format floating-point values on output operations.
#include <iostream>
using namespace std;
#include <iomanip> // std::setprecision
int main() {
float a, b, average;
cin >> a;
cin >> b;
average = (a+b)/2;
cout << fixed << setprecision(2) << average << endl;
}
I'm trying to get an output for my weight_Fee using double, and I cannot seem to get the correct value. I have tried using float, but I haven't been able to get that to work either.
My goal is to get an output value containing two decimal places as if I were to be calculating a cost, but I get 0.00 every time.
I'm new to C++, so if anyone can tell me what I'm doing wrong, it would be a big help. Thanks.
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
double animal_Weight;
double weight_Fee = .5 * animal_Weight;
cout << "In rounded poundage, how much does your animal weigh? ";
cin >> animal_Weight;
cout << setprecision (2) << fixed << weight_Fee;
return 0;
}
double weight_Fee = 0.5 * animal_Weight;
When you initialize weight_Fee like that you are setting it equal to 0.5 * the current value of animal_Weight. Since this is currently undefined weight_Fee will be some garbage value.
When you set animal_Weight to something based on user input later on, that won't change the value of a previous variable. You'll have to use that statement again to set weight_Fee = 0.5 * the current value of animal_Weight
The best thing to do is probably to just declare weight_Fee at the top, and not define it until you have set animal_Weight to what you want it to be.
Something like this:
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
double animal_Weight;
double weight_Fee;
cout << "In rounded poundage, how much does your animal weigh? ";
cin >> animal_Weight;
weight_Fee = .5 * animal_Weight
cout << setprecision (2) << fixed << weight_Fee;
return 0;
}
The variable animal_Weight is undefined and can be initialized to anything by the compiler or the operating system or whatever value happen to be last in the memory.
You need to calculate weight_Fee after you input a value for animal_Weight:
double animal_Weight = -1.0;
cout << "In rounded poundage, how much does your animal weigh? ";
cin >> animal_Weight;
double weight_Fee = .5 * animal_Weight;
cout << setprecision (2) << fixed << weight_Fee;
Either someone forgot to mention to you that your computer does only 1 instruction at a time (and the C++ compiler generates instructions in a sequence corresponding to your code); or perhaps you've never grok'ed the statement.
1) double animal_Weight;
2) double weight_Fee = .5 * animal_Weight;
3) cout << "In rounded poundage, how much does your animal weigh? ";
4) cin >> animal_Weight;
5) cout << setprecision (2) << fixed << weight_Fee;
Your code prompts for (3) and cin's (4) an animal weight. ok.
But the weight_Fee was computed (2) prior to knowing the animal_Weight (4). This is a logic error.
So if the computation at (2) did not know the animal_Weight, the correct value simply can not be determined.
Also, the animal_Weight (1) is not initialized, creating undefined behaviour.
Note that you CAN get the compiler to complain about (generate a warning) the attempted use of an uninitialized variable (at line 2), but you have to command the compiler to do so (by using an option).
I need to write need a function to compute power in C++
I don't understand why my code below is wrong.
ex. : base: 2 exponent 3 -> result: 4.48498e-306
if i use "int" the result is -> 2
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
double power(double base, double exponent);
int main()
{
double base, exponent, power;
cout << "Enter a base " << endl;
cin >> base;
cout << "Enter an exponent" << endl;
cin >> exponent;
cout << "The result is ': "<< power << endl;
return 0;
}
double power(double base, double exponent)
{
int i;
double s=1;
for (i = 0; i < exponent; ++i)
s *= base;
return s;
}
What am I doing wrong?
In your code you have two declarations of power.
double power(double base, double esponente);
double base,esponente,power;
You declare the variable power but you never initialize it before printing it, so it's going to be undefined. Rerunning your program will actually give you a different number, in all likelihood. You need to remove this local variable declaration, as it shadows the global function declaration.
Then, instead of
cout<<"\nL'elevamento a potenza e': "<<power<<endl;
You want this line:
cout<<"\nL'elevamento a potenza e': "<<power(base, esponente)<<endl;
You are either printing the address of the function power or printing the uninitialized value of the double power the way you have written the code. (Technically you are hitting an uninitialized shadowed variable). In any case, you are not even calling the function you wrote... How does the power function know to be called? With what arguments?
Fix 1. Suggest you delete the 'double' of power.
Fix 2. Actually call the function and use/store/print the result
example.
After getting input from user do this:
double result = power( base, exponent );
cout << result << endl;
To print the result.
You need call function like this, with parameters:
Here is your main. You don't need local variable power. You want call function with name power.
int main ()
{
double base,esponente;
cout<<" \n Inserisci base \n";
cin>>base;
cout<<"\nInserisci esponente\n";
cin>>esponente;
cout<<"\nL'elevamento a potenza e': "<<power(base,esponente)<<endl;
system ("PAUSE");
}
Why is the output of these two programs different? I have included the code so you can easily view it and try it. Can anyone explain it to me?
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float pi = 3.14159;
int r;
while (cin >> r) {
cout << "VOLUME = " << fixed << setprecision(3)
<< pi*r*r*r*(4.0/3.0) << endl;
}
return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float pi = 3.14159;
int r;
while (cin >> r) {
cout << "VOLUME = " << fixed << setprecision(3)
<< (4.0/3.0)*r*r*r*pi << endl;
}
return 0;
}
If I input 1523 the first one gives me 14797487059.353, which is the right answer, but the second one gives a negative number.
The 2 screens with the outputs this link include the 2 outputs the first one ir the right the second one is weird !
The code in your screenshot is not what you've posted here. I'd advise that in the future, if you want help with a problem you're having, you post the code you're having problems with - not code that's completely different.
In this case, the problem is simple - r*r*r is too big to fit inside of one int. You can change r to be type long long and this issue should go away. Alternatively, you can use either of the two blocks of code you've posted here, as they both work as you expect.