Click here to Skip to main content
15,887,268 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Getting the code to solve the question

What I have tried:

Using math library, what is y=(2xcosx)^1/2 / (sinx)^1/2 ?
Posted
Updated 12-Oct-23 9:42am
v2
Comments
jeron1 10-Oct-23 15:54pm    
Maybe take a look at functionality included with this header.
https://cplusplus.com/reference/cmath/

I recommend that you start with a tutorial like this one : cplusplus.com tutorial[^].

The part that is "^1/2" is probably the square root. You can obtain that by calling the function sqrt[^]. You will also need these two functions : cos[^] and sin[^].

By reading the tutorial you should learn out to call functions and utilize the computation operators for multiplication and division.
 
Share this answer
 
You can rewrite your expression as
y(x) = ((2 x cosx)/sinx)^(1/2)


Then, in C++

C++
y = sqrt( 2 * x * cos(x) / sin(x))


Try
C++
#include <iostream>
#include <cmath>

int main()
{
	double x = M_PI/3;
	
	double y = sqrt( 2 * x * cos(x) / sin(x));
	
	std::cout << "x = " << x << ", y(x) = " << y << std::endl;
	
}
 
Share this answer
 
v2
Comments
Kenneth Haugland 12-Oct-23 8:09am    
You could also replace cos(x)/sin(x) with either cot(x) or 1/tan(x), but I dont know if that will be better.
merano99 12-Oct-23 11:03am    
You wanted to say cos(x)/sin(x) = tan(x)?
Richard Deeming 12-Oct-23 11:14am    
That's not right - cos/sin = 1/tan, as Kenneth said.

Going back to high-school geometry:
* cos = A/H
* sin = O/H
* tan = O/A

So: cos/sin === (A/H)/(O/H) === A/O === 1/tan
merano99 12-Oct-23 11:41am    
yes, that's right, I read it wrong.
Changing the formula and taking the square root only once has already been mentioned as a tip. In addition, you should take care that no division by zero occurs.
C++
double mycalc(double x) 
{
    double sin_x = std::sin(x);

    if (sin_x == 0.0) {
        return std::numeric_limits<double>::quiet_NaN();
    }

    double temp = 2.0 * x * std::cos(x) / sin_x;

    if (temp < 0.0) {
        return std::numeric_limits<double>::quiet_NaN();
    }

    return std::sqrt(temp);
}

Perhaps you can write it with tan(x) = sin(x)/cos(x) more performant.
 
Share this answer
 
v6
Comments
0x01AA 12-Oct-23 7:46am    
Similar should be tested for sqrt of negative values.
merano99 12-Oct-23 9:25am    
Yes, of course. Thanks for the addition!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900