Here's the code.
int a;
int pi = 3.14;
int area;
int main()
{
cout << "Input the radius of the circle ";
cin >> a;
a *= a *= pi >> area;
cout << "The area is " << area;
}
The >> operator when used with numbers is right shift, not assignment. You want something like
area = a * a * pi;
Update
You also need to use a floating point type or your answer won't be what you expect.
float a;
float pi = 3.14f;
float area;
I don't have enough patience to decipher your strange code. How about just area = a * a * pi?
Your code doesn't make any sense.
pi(and all your other variables) need to be double or float,... not int. An int can only contain an integral number. And pi is obviously not integral.
a *= a *= pi >> area; should be area = a * a * pi;
>> is a bitshift, not an assignment to the right side
*= is multiply assign and not just multiply. i.e. it is similar to left=left*right
The area of a circle is pi * r * r therefore you would want to do;
a = a * a * pi
Hope that helps
and they all would need to be floats.
Your code doesn't do what I think you wanted it to do. You don't assign to variables with >>; that is only for stream extraction (and bitshifting).
Also, a *= a *= pi probably doesn't do what you think it does.
Also, you want floating-point values, not int. An "int" pi is just 3.
Also, you should have error checking on your stream extraction!
Try:
int main()
{
const float pi = 3.14;
float a;
cout << "Input the radius of the circle ";
if (!(cin >> a)) {
cout << "Invalid radius!";
return 1;
}
float area = (a * a * pi);
cout << "The area is " << area;
}
int pi = 3.14;
Wrong datatype. Assigning double value to int? That's wrong.
Write this:
double pi = 3.14;
And likewise, change other datatypes to double as well.
Because you're using int, or integer, for all your variables. You want to use doubles or even floats. (doubles are more precise).
All your variables are declared as int, which simply drops any fractional portion assigned to it. To work with floating-point values, use double instead.
Also, your equation in almost incomprehensible. Not sure what you're trying to do there.
Related
I have a c++ program which calculates Pi but then its value gets cut off after a few decimal places because of the decimal place limit on the float which Pi is stored in.
I've already tried using different data types instead of float but they still have a decimal place limit which is too small.
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main(){
cout << "Calculate Pi using the Nilakantha series" << endl << endl;
unsigned long int iterations = 0;
unsigned long int x = 0;
unsigned long int y = 2;
char z = 0;
string fileName = "";
int64_t Pi = {3.0f};
cout << "Input the number of loop iterations(maximum of 4,294,967,295): ";
cin >> iterations;
cout << "Input the name of the file you want to write to: ";
cin >> fileName;
for(x = 0; x < iterations; x++){
Pi += 4.0f / (y * (y + 1.0f) * (y + 2.0f));
y += 2;
Pi -= 4.0f / (y * (y + 1.0f) * (y + 2.0f));
y += 2;
}
ofstream file;
file.open(fileName + ".txt");
file << Pi;
file.close();
cout << endl << "Calculation complete, check the file " << fileName << ".txt";
cin >> z;
}
How do I remove the limit or use a method which stores the value of Pi without it getting cut off after a few decimal places?
There are a few big issues here. The first is that you're using std::cout to print the value, and std::cout only prints 6 digits by default. The second is that you declared Pi as an int64_t. That means you'll get at most 1 digit of precision, since Pi is an integer. You need to have it as a floating point type.
So how many digits will you get from each type?
6 digits from float
15-16 digits from double
20 digits from long double on clang and gcc, but only 15-16 in Visual Studio
Around 30 digits from GCC's __float128, although that one only works on GCC
If you want more precision than that, you're going to have to use a high-precision arithmetic library that gives you more digits by simulating it. It won't be as fast, but it'll do the job.
You can play around with the amount of precision with each type using this code. I templated calculatePi on the type, so you can just stick in float, double, long double, or __float128. It'll print 20 digits. This code should print all 20 digits correctly for __float128.
#include <cstdio>
using namespace std;
template<class Float>
Float calculatePi(size_t iterations) {
Float y = 2;
Float Pi = 3;
const Float two = 2;
const Float four = 4;
const Float one = 1;
for(size_t i = 0; i < iterations; i++) {
Pi += four / (y * (y + one) * (y + two));
y += two;
Pi -= four / (y * (y + one) * (y + two));
y += two;
}
return Pi;
}
int main(){
long double result = calculatePi<long double>(1000000);
printf("Expected: 3.14159265358979323846\n");
printf("Actual: %.20Lf", result);
}
(I'm ignoring some of the less fundamental issues which #JAntonioPerez points out in his fine answer and focusing on what I find to be the core of this question.)
If you just need a few more decimal digits of precision, then use double or long double instead of float.
If you want much higher precision, or a precision which can be specified as a run-time or compile-time arbitrary value, then you need something else. Either:
Use an arbitrary-precision number data type; here is a list of libraries providing such types.
Instead of iterating over the entire number, use iteration to determine the value of individual digits/characters in the output; and write the digits you obtain to the output file one at a time (or a few at a time).
Of course, both options are rather involved and are probably not appropriate for a "toy program" like you seem to be writing.
so hey guys, I thought to make a simple program to learn about functions and I ran across this error I never had before could someone help me?
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
float SphereVolume(float r);
int main() {
/*
Calculating a sphere.
*/
float radius;
cout << "Sphere Calc....\n";
cout << "\tPlease Enter Radius of Sphere: ";
cin << radius;
SphereVolume(radius);
return 0;
}
float SphereVolume(float r) {
double const PI = 3.14159;
float volume;
volume = 4/3 * PI * r ^ 3; // error starts here.
return volume;
}
I cant seem to understand why this is happening, the error, start when I try to declare the volume equation and it says the error??
volume = 4/3 * PI * r ^ 3; // error starts here.
4 / 3 is integer division -> 1
r ^ 3 is r xor-ed with the integer 3.
You can't xor a float. If you want to cube a float, the simplest solution is to multiply it three times.
you've got two errors and the first one gives you probably a wall of error codes:
cin << radius;
proper construction is:
cin >> radius;
Second error is the one you're actually asking of:
volume = 4 / 3 * PI * r ^ 3;
^ - is a xor operator that don't work on float types.
The resulting type from 4/3*PI*r is double. You cannot do xor (^) on it.
I think you actually tried to get the result to the power of three. In C++ there is no simple operator that can do it. You can use pow(..) function like this:
volume = pow(4 / 3 * PI * r, 3);
Remeber to add #include <cmath> to be able to use the function.
doing a school project. i do not understand why the sin comes out to -NaN when after sin(90) and cos(120).
Can anyone help me understand this?
Also, when I put this in an online C++ editor it totally works, but when compiled in linux it does not.
// Nick Garver
// taylorSeries
// taylorSeries.cpp
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
const double PI = atan(1.0)*4.0;
double angle_in_degrees = 0;
double radians = 0;
double degreesToRadians(double d);
double factorial(double factorial);
double mySine(double x);
double myCosine(double x);
int main()
{
cout << "\033[2J\033[1;1H";
cout.width(4); cout << left << "Deg";
cout.width(9); cout << left << "Radians";
cout.width(11); cout << left << "RealSine";
cout.width(11); cout << left << "MySin";
cout.width(12); cout << left << "RealCos";
cout.width(11); cout << left << "MyCos"<<endl;
while (angle_in_degrees <= 360) //radian equivalent of 45 degrees
{
double sine = sin(degreesToRadians(angle_in_degrees));
double cosine = cos(degreesToRadians(angle_in_degrees));
//output
cout.width(4); cout << left << angle_in_degrees;
cout.width(9); cout << left << degreesToRadians(angle_in_degrees);
cout.width(11); cout << left << sine;
cout.width(11); cout << left << mySine(degreesToRadians(angle_in_degrees));
cout.width(12); cout << left << cosine;
cout.width(11); cout << left << myCosine(degreesToRadians(angle_in_degrees))<<endl;
angle_in_degrees = angle_in_degrees + 15;
}
cout << endl;
return 0;
}
double degreesToRadians(double d)
{
double answer;
answer = (d*PI)/180;
return answer;
}
double mySine(double x)
{
double result = 0;
for(int i = 1; i <= 1000; i++) {
if (i % 2 == 1)
result += pow(x, i * 2 - 1) / factorial(i * 2 - 1);
else
result -= pow(x, i * 2 - 1) / factorial(i * 2 - 1);
}
return result;
}
double myCosine(double x)
{
double positive = 0.0;
double negative= 0.0;
double result=0.0;
for (int i=4; i<=1000; i+=4)
{
positive = positive + (pow(x,i) / factorial (i));
}
for (int i=2; i<=1000; i+=4)
{
negative = negative + (pow(x,i) / factorial (i));
}
result = (1 - (negative) + (positive));
return result;
}
double factorial(double factorial)
{
float x = 1;
for (float counter = 1; counter <= factorial; counter++)
{
x = x * counter;
}
return x;
}
(Marcus has good points; I am going to ramble in other directions...)
Look at the terms in a Taylor series. They become too small to make any difference after fewer than 10 terms. Asking for 1000 is asking for trouble.
Instead of going for 1000, go until the next term does not add anything, something like:
term = pow(x, i * 2 - 1) / factorial(i * 2 - 1);
if (result + term == result) { break; }
result += term;
The series would run much faster if you iteratively calculated the pow and factorial rather than starting over each time. (But, probably speed is not an issue at this point.)
Float has 24 bits of binary precision. Beginning perhaps with 13!, you will get roundoff errors in float. Double, on the other hand, has 53 bits of precision and will last until about 22! without roundoff errors. My point is that you should have done factorial() in double.
Another problem is that the computation of the Taylor series gets somewhat 'unstable' for bigger arguments. Intermediate terms become bigger than the end result, thereby leading to other roundoff errors. To avoid this, a common way to compute sine and cosine is to first fold to between -45 and +45 degrees. No unfolding, except maybe for the sign, is needed later.
As for why you had trouble on one system but not the other -- Different implementations handle NaN differently.
Once you have gotten the NaN out of the way, try computing the series in reverse order. This will lead to a different set of roundoff errors. Will it make your sin() closer to the real sin?
The 'real' sin is probably computed in hardware with 64-bit fixed-point arithmetic, and will be "correctly rounded" to 53 or 24 bits well over 99% of the time. (This, of course, depends on the chip manufacturer, hence my 'hand-waving' statement.)
To judge how 'close' your value is, you need to compute ULPs (units in the last place). This involves looking at the bits in the float/double. (Beyond the scope of this question.)
Sorry about the TMI.
Before I answer this, a few remarks:
It's always helpful for your own debugging to keep your code tidy. Remove unnecessary empty lines, make sure your bracketing style is uniform, and properly indent. I did this for you, but believe me, you'll avoid a lot of bugs if you keep up a consistent style!
you have functions that take double as input and return double, but internally just use float; that should be a red flag!
your whole degreesToRadians would be better to read and only one third as long if you just used return (d*PI)/180;
Answers now:
in your factorial function, you calculate a factorial for values up to 1999. Hint: try to figure out the value of 1999! and look up the maximum number that float on your machine can hold. Then look up double's maximum. How many orders of magnitude is 1999! larger?
1999! is ca. 10^5732. That is a large number, about 150 orders of magnitude larger than what a 32bit float can hold, or still 18 orders of magnitude larger than what a 64bit double can hold. To compare, to store 1999! in a double would be like trying to fit the distance from sun center to earth center in the typical 0.1µm diameter of bacteria.
I want to save the value of a float variable named f in the third element of an array named i in a way that the floating point part isn't wiped (i.e. I don't want to save 1 instead of 1.5). After that, complete the last line in a way that we see 1.5 in the output (don't use cout<<1.5; or cout<<f; or some similar tricks!)
float f=1.5;
int i[3];
i[2] = ... ;
cout<<... ;
Does anybody have any idea?
Use type-punning with union if they have the same size under a compilation environment:
static_assert(sizeof(int) == sizeof(float));
int castFloatToInt(float f) {
union { float f; int i; } u;
u.f = f;
return u.i;
}
float castIntToFloat(int i) {
union { float f; int i; } u;
u.i = i;
return u.f;
}
// ...
float f=1.5;
int i[3];
i[2] = castFloatToInt(f);
cout << castIntToFloat(i);
Using union is the way to prevent aliasing problem, otherwise compiler may generate incorrect results due to optimization.
This is a common technique for manipulating bits of float directly. Although normally uint32_t will be used instead.
Generally speaking, you cannot store a float in an int without loss of precision.
You could multiply your number with a factor, store it and after that divide again to get some decimal places out of it.
Note that this will not work for all numbers and you have to choose your factor carefully.
float f = 1.5f;
const float factor = 10.0f;
int i[3];
i[2] = static_cast<int>(f * factor);
std::cout << static_cast<float>(i[2]) / factor;
If we can assume that int is 32 bits then you can do it with type-punning:
float f = 1.5;
int i[3];
i[2] = *(int *)&f;
cout << *(float *)&i[2];
but this is getting into Undefined Behaviour territory (breaking aliasing rules), since it accesses a type via a pointer to a different (incompatible) type.
LIVE DEMO
I was till was experiencing some issues until i made the change to my formula for gravity. all is working now. thanks everyone. I appreciate all the great feedback
#include <iostream>
#include <string>
#include <cstdlib>
#include <cmath>
using namespace std;
int main()
{
// Initialize objects:
double angle = 0.0;
double velocity = 0.0;
double range = 0.0;
const double PI = 3.141592653589793238;
const double gravity = 9.8; //meters pers second
// Input:
cout << "takeoff angle: ";
cin >> angle;
cout << "Please enter velocity: ";
cin >> velocity;
// Process
angle = angle * PI / 180;
range = sin(2 * angle) * velocity * velocity / gravity;
cout << " range " << range << endl;
system("pause");
return 0;
}
range = sin(* angle)*velocity pow(2);
This is not valid C++.
pow is a function that takes two arguments. x^y would be represented as pow(x, y).
Also, sin(*angle) is invalid as angle is neither a pointer nor a class with a defined * operator.
I think this is what you're looking for:
range = sin(2 * angle) * velocity * velocity / gravity;
// (No need to use pow(velocity, 2) over velocity * velocity)
(This is the correct formula for range)
You defined angle as a double, so you don't want to dereference it by writing *angle.
pow() takes two arguments, so you probably want to write pow(velocity,2).
sin(angle)*pow(velocity,2) should work. I'd recommend sin(angle)*velocity*velocity, as you don't need to use pow(x,2) if you only want to calculate x*x.
Oh, and note that gravity is 0.0 in your code, as it is defined as velocity*9.8 while velocity is 0.0.