atanf gives me wrong answers - c++

I was doing Exercise of Chapter 3 (Functions) from a Book Called C++ Modules for Gaming.
It is this one question I am not able to Do is to find atanf(4/2) of (2,4) which according to the book and my calculator should give back '63.42' degrees.
Instead it gives me 1.107 degrees.
Here is my code:
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
void tani(float a,float b) //Finds the Tan inverse
{
float res;
res = atanf(b / a);
cout << res << endl;
}
int main()
{
cout << "Enter The Points X and Y: " << endl;
float x, y;
cin >> x >> y; //Input
tani(x,y); //calling Function
}

atanf, and the other trigonometric functions in c++ return results in radians. 1.107 radians are 63.426428 degress, so your code is correct.
You can convert radians to degrees by multiplying by 180 and dividing by Pi (the M_PI constant provided by <cmath>):
cout << res * 180.0 / M_PI << endl;

It is giving you correct answer in radians.Simply Convert it to Degree!
void tani(float a, float b) //Finds the Tan inverse
{
float res;
res = atanf(b/ a);
cout << res *(180 / 3.14) << endl;
}

Related

Euler method in c++; Values getting too big too fast

i am trying to solve the equation of motion for a particle with mass m attached to a spring with a spring constant k. Both are set to 1 however.
The algorithm looks like this:
My (attempted) solution, written in c++, looks like this:
#include <iostream>
#include <iomanip>
#include <math.h>
#include <stdlib.h>
#include <fstream>
// Initialise file to write series of values in
std::ofstream output("Eulermethod.txt");
// Define Euler algorithm
void euler(double x_0, double v_0, double delta, double t_max) {
double x_prev = x_0;
double v_prev = v_0;
double x_new, v_new;
for (double t = 0; t < t_max; t = t + delta) {
x_new = x_prev + t * v_prev;
v_new = v_prev - t * x_prev;
// Writes time, position and velocity into a csv file
output << std::fixed << std::setprecision(3) << t << "," << x_prev << "," << v_prev << std::endl;
x_prev = x_new;
v_prev = v_new;
// Breaks loop if values get to big
if ((x_new != x_new) || (v_new != v_new) || (std::isinf(x_new) == true) || (std::isinf(v_new) == true)) {
break;
}
}
}
int main() {
// Initialize with user input
double x_0, v_0, t_max, delta;
std::cout << "Initial position x0?: ";
std::cin >> x_0;
std::cout << "Intial velocity v0?: ";
std::cin >> v_0;
std::cout << "Up to what time t_max?: ";
std::cin >> t_max;
std::cout << "Step size delta?: ";
std::cin >> delta;
// Runs the function
euler(x_0, v_0, delta, t_max);
}
I know that the solution will grow indefinitely but for smaller values of t it should resemble the analytical solution while growing slowly.
The values i get are blowing out of proportions after ca. 10 iterations and i can not find out why.
When i plot the position as a function of the time i get the plot below, which is obviously wrong.
Your equation implementation is wrong. You are usint t instead of dt. Correct variant:
x_new = x_prev + delta * v_prev;
v_new = v_prev - delta * x_prev;
And a side note if you plan to develop your code further: common approach to implementation of ODE solver is to have a method with signature similar to
Output = solveOde(System, y0, t);
Where System is method that describes the ODE dy/dx = f(x,t), e.g.
std::vector<double> yourSystem(std::vector<double> y, double /*t unused*/)
{
return {y[1], -y[0]};
}
y0 are initial conditions, and t is a time vector (delta is calculated internally). Take a look at boost odeint or more compact and transparent python documentation.

Did I use Xcode incorrectly or I wrote the program incorrectly?

So I am doing a C++ question about sine.
It says that sin x can be approximated via the polynomial x-(x^3/6)+(x^5/120)-(x^7/5040), and it tells me to output both the approximated sin value and the sin value calculated via cmath.
The input is in degrees, and we have to first convert it to radians then find out sin.
Sample run (only 45 is the input, other our output):
Angle: 45
approxSin = 0.70710647
cmath sin = 0.70710678
I have attempted to write a code for this. When I pressed command+R, nothing happens despite the program saying "build successful". I am new to Xcode, so I am not sure whether I used Xcode incorrectly or I wrote the program incorrectly. Can anyone help?
#define _USE_MATH_DEFINES
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double approxSin(double angleDeg) {
if (-180<angleDeg<180) return approxSin(angleDeg-(angleDeg*angleDeg*angleDeg)/6+(angleDeg*angleDeg*angleDeg*angleDeg*angleDeg)/120-(angleDeg*angleDeg*angleDeg*angleDeg*angleDeg*angleDeg*angleDeg)/5040);
}
int main(){
float angleDeg;
cin >> angleDeg;
if (angleDeg>180) {
while (angleDeg>180) {
angleDeg = angleDeg-360;
}
} else if (angleDeg<-180) {
while (angleDeg<-180) {
angleDeg = angleDeg+360;
}
}
cout << "approxSin = " << &approxSin << endl;
cout << "cmath sin = " << setprecision(8) << sin(angleDeg);
return 0;
}
my code
My guess about your problem: You run the program, and it patiently waits for your input.
With
cin >> angleDeg;
your program seemingly halts, while it's waiting for you to give some input in the IDE console window. Since you haven't written any prompt there's no output to tell you it's waiting for input.
I suggest you add some output first to ask for the input:
cout << "Please enter angle in degrees: ";
cin >> angleDeg;
When I pressed command+R, nothing happens despite the program saying "build successful".
I guess that the answer by Some programmer dude should solve this issue, but, as noted in the comments, there are much worse problems in the posted code, probably depending by a misunderstanding of how functions should be declared and called in C++.
Consider this:
double approxSin(double angleDeg) {
if (-180<angleDeg<180) return approxSin(/* Some unreadable expression */);
}
It's enough to generate a couple of warning:
prog.cc:7:22: warning: result of comparison of constant 180 with expression of type 'bool'
is always true [-Wtautological-constant-out-of-range-compare]
if (-180&ltangleDeg&lt180) return approxSin(angleDeg-(...));
~~~~~~~~~~~~~^~~~
prog.cc:6:35: warning: all paths through this function will call itself [-Winfinite-recursion]
double approxSin(double angleDeg) {
^
The relational operators are evaluated left-to-right, so that an expressions like -180<angleDeg<180 is read by the compiler as (-180 < angleDeg) < 180. The result of -180 < angleDeg is a bool which leads to the kind warning by the compiler about that expression beeing always true.
It could be written as -180 < angle && angle < 180, but given the OP's assignment, the angle should be tested against plus or minus pi. Also, the alternative branch should be written as well.
The second warning is about the recursive call of the function, which makes no sense, without any alternative path. I can only guess that the OP has misinterpreted how values are returned from a function.
The polynomial itself could be evaluated in a more readable way using std::pow or applying Horner's method. I'll show an example later.
The other big problem (specular, someway) is in the "call" site, which isn't a call at all:
cout << "approxSin = " << &approxSin << endl;
It ends up printing 1 and the reasons can be found in this Q&A: How to print function pointers with cout?
Last, I'd note that while the assignment specifically requires to convert the inputted angle from degrees to radians (as the argument of std::sin is), the posted code only checks the range in degrees, without any conversion.
The following implementation compares different methods for evaluating the sin() function
#define _USE_MATH_DEFINES
#include <iostream>
#include <iomanip>
#include <cmath>
namespace my {
// M_PI while widespread, isn't part of the ISO standard
#ifndef M_PI
constexpr double pi = 3.141592653589793115997963468544185161590576171875;
#else
constexpr double pi = M_PI;
#endif
constexpr double radians_from_degrees(double degrees)
{
return degrees * pi / 180.0;
}
constexpr double convert_angle_to_plus_minus_pi(double angle)
{
while ( angle < -pi )
angle += 2.0 * pi;
while ( angle > pi ) {
angle -= 2.0 * pi;
}
return angle;
}
// Approximates sin(angle), with angle between [-pi, pi], using a polynomial
// Evaluate the polynomial using Horner's method
constexpr double sin_a(double angle)
{
// A radian is passed, but the approximation is good only in [-pi, pi]
angle = convert_angle_to_plus_minus_pi(angle);
// Evaluates p(a) = a - a^3 / 6 + a^5 / 120 - a^7 / 5040
double sq_angle = angle * angle;
return angle * ( 1.0 + sq_angle * (-1.0/6.0 + sq_angle * ( 1.0/120.0 - sq_angle / 5040.0)));
}
double sin_b(double angle) {
angle = convert_angle_to_plus_minus_pi(angle);
return angle - pow(angle, 3) / 6.0 + pow(angle, 5) / 120.0 - pow(angle, 7) / 5040.0;
}
} // End of namespace 'my'
int main()
{
std::cout << " angle std::sin my::sin_a my::sin_b\n"
<< "-----------------------------------------------\n"
<< std::setprecision(8) << std::fixed;
for (int i = -90; i < 475; i += 15)
{
double angle = my::radians_from_degrees(i);
std::cout << std::setw(5) << i
<< std::setw(14) << std::sin(angle)
<< std::setw(14) << my::sin_a(angle)
<< std::setw(14) << my::sin_b(angle) << '\n';
}
return 0;
}

C++ program to build a Trigonometric Calculator

I am novice at programming in C++. I want to write a program using while loop which displays the trigonometric table for sin, cos and Tan. It takes angles in degrees with a difference of 5 and displays the result. This it what I tried,
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int num;
cout<< "Angle Sin Cos Tan"<<endl;
cout<< "..........................."<<endl;
num=0;
while (num<=360)
{
cout <<setw(3)<<num<<" "
<<setw(3)<<setprecision(3)<<sin(num)<<" "
<<setw(3)<<setprecision(3)<<cos(num)<<" "
<<setw(5)<<setprecision(3)<<tan(num)<<endl;
num=num+5;
}
}
Unfortunately, I could not change radians into degrees in while loop and the display does not look promising even for radians. How can I resolve it ?
To convert degrees to radiant you have to multiply by pi and to divide by 180.0:
#define M_PI 3.14159265358979323846
int num = 0;
while (num<=360)
{
double numRad = num * M_PI/180.0;
std::cout <<std::setw(3)<<num<<" "
<<std::setprecision(3)<<std::fixed
<<std::setw(6)<< std::sin( numRad ) <<" "
<<std::setw(6)<< std::cos( numRad ) <<" ";
if ( num != 90 && num != 270 )
std::cout<<std::setw(6)<< std::tan( numRad ) <<std::endl;
else
std::cout<< "infinitely" <<std::endl;
num=num+5;
}
To use constant M_PI see How to use the PI constant in C++
To convert degrees to radians, use numRad = M_PI / 180.0 where M_PI should be a constant that holds the value od Pi. If you do not have such a constant defined in a header file, just define it yourself, like #define PI 3.14159265
The functions sin, cos and tan always require arguments in radians.

Getting error "invalid operands of types `float' and `int' to binary `operator^'" C++

Keep getting error "invalid operands of types float' andint' to binary `operator^' when compiling. I believe it is an issue with the 4/3 but I'm unsure how to make it work. I think I am just missing a simple part of code but have spent over an hour trying to figure it out
#include <iostream>
#define Pi 3.14159265359
using namespace std;
float SphereVol (float r)
{
float vol;
vol = ((4/3)*(Pi)*(r^3));
return vol;
}
int main()
{
float r, f = SphereVol(r);
for (r=0; r=4; r+(.2))
{
cout.precision(7);
cout << "Radius: " << r << " volume: " << SphereVol(r) << endl;
}
system("pause");
return 0;
}
I've edited the code from above and now it is having problems displaying correctly and for some reason the cout.precision(8) is making the output come out with the decimal places incorrect. It is supposed to list like
radius= 4.0000000 volume= .xxxxxxx
but is leaving decimal off whole numbers.
#include <iostream>
#define Pi 3.1415926
using namespace std;
float SphereVol (float r)
{
float vol;
vol = ((4.0/3.0)*(Pi)*(r*r*r));
return vol;
}
int main()
{
float r;
float f = SphereVol(r);
for (r = 0; r <= 4; r += .2)
{
cout.precision(8);
cout << "Radius: " << r << " volume: " << SphereVol(r) << endl;
}
cout << endl;
system("pause");
return 0;
}
Decimals are now displaying
Example: radius= 3.20000005
radius= 3.40000006
It is supposed to display like
Radius: 0.200000 volume: 0.033503
Radius: 0.400000 volume: 0.268082
Radius: 0.600000 volume: 0.904778
Radius: 0.800000 volume: 2.14466
Radius: 1.000000 volume: 4.18879
In C++ (and also in C), the ^ operator is the bit-wise eXclusive OR (XOR) operator that only works on integer types.
It is not a power operator to raise a number to a power.
You could rewrite your function like:
float SphereVol (float r)
{
return (float) (4.0 / 3.0 * Pi * r * r * r);
}
In your code, the expression (4/3) will be done with integer math, which discards any remainder and will evaluate to 1. In my code above, I use 4.0 and 3.0 to force double precision floating point math to be done for the division and following multiplications. I then cast that double precision result to a single precision float to match the function's return type.
For more generally raising a number to a power, there are the std::pow functions if you #include <cmath>: http://en.cppreference.com/w/cpp/numeric/math/pow
Make sure that float has enough precision for your math. You may prefer to use double instead, which has more precision.
Also, your loop syntax is wrong. The way you wrote it will cause an infinite loop. Try this instead:
for (r = 0; r <= 4; r += 0.2)

Convert radians to degrees like Google

Im trying to convert radians to degrees, but im not getting the same results as google
calculator and the Pi i defined dosent output all number.
If you type in google search: (1 * 180) / 3.14159265 then you get 57.2957796, but my program is
outputting: 57.2958 and if you type in google search Pi you get: 3.14159265, but mine
dosent output the rest, it output: 3.14159
My code is:
#include <iostream>
#define SHOW(X) cout << # X " = " << (X) << endl
using namespace std;
double Pi_test = 3.14159265;
float radian_to_degree(double ENTER) {
double Pi = 3.14159265;
float degrees = (ENTER * 180) / Pi;
return degrees;
}
int main (int argc, char * const argv[]) {
SHOW( radian_to_degree(1) ); // 57.2958 not 57.2957795 like google, why?
SHOW( Pi_test ); // output 3.14159' not 3.14159265, why?
return 0;
}
Please help me fix this, what wrong? any example?
You need to change the default precision:
cout.precision(15);
cout << d << endl;
As stated here, it may be that cout in C++ is rounding your number before displaying it. Try this:
#define SHOW(X) cout << setprecision(some_number) << # X " = " << (X) << endl
Change radian_to_degree to operate on double not float, since double has more precision.
Output the result using std::setprecision
#include <iomanip>
std::cout << std::setprecision(9) << result << "\n";
Even after you change cout's precision, note that double only contains so much data; if you expect your program to spit out 1000 decimal places, a double is not going to give you that much. You'd have to create a data type of your own.
Also, don't define macro functions unless you have to.