0% found this document useful (0 votes)
54 views11 pages

C++ Math Functions Practice Solutions

The document provides a series of C++ programs that demonstrate various mathematical functions, including basic arithmetic, trigonometric functions, logarithmic and exponential functions, and rounding operations. Each program includes user input and outputs results for operations such as power, square root, logarithm, and trigonometric calculations. Additionally, it explains concepts like floating-point precision and the differences between certain functions.

Uploaded by

kabulamwenda20
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views11 pages

C++ Math Functions Practice Solutions

The document provides a series of C++ programs that demonstrate various mathematical functions, including basic arithmetic, trigonometric functions, logarithmic and exponential functions, and rounding operations. Each program includes user input and outputs results for operations such as power, square root, logarithm, and trigonometric calculations. Additionally, it explains concepts like floating-point precision and the differences between certain functions.

Uploaded by

kabulamwenda20
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C++ Math Functions - Practice Problem Solutions

Basic Arithmetic and Power

1. Write a program to calculate x^y using pow()

cpp

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double x, y;

cout << "Enter base (x): ";


cin >> x;
cout << "Enter exponent (y): ";
cin >> y;

double result = pow(x, y);


cout << x << " raised to power " << y << " = " << result << endl;

return 0;
}

2. Take a number and print its square root

cpp

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double num;

cout << "Enter a number: ";


cin >> num;

double squareRoot = sqrt(num);


cout << "Square root of " << num << " = " << squareRoot << endl;

return 0;
}
3. Find the cube root of a number using cbrt()

cpp

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double num;

cout << "Enter a number: ";


cin >> num;

double cubeRoot = cbrt(num);


cout << "Cube root of " << num << " = " << cubeRoot << endl;

return 0;
}

4. Compute the result of 5^3 + sqrt(81)

cpp

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double result = pow(5, 3) + sqrt(81);

cout << "5^3 + sqrt(81) = " << result << endl;

return 0;
}

5. Compare pow(x, 0.5) with sqrt(x) — are the results always the same?
cpp

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

int main() {
double x;

cout << "Enter a number: ";


cin >> x;

double result1 = pow(x, 0.5);


double result2 = sqrt(x);

cout << fixed << setprecision(15);


cout << "pow(" << x << ", 0.5) = " << result1 << endl;
cout << "sqrt(" << x << ") = " << result2 << endl;

if (result1 == result2) {
cout << "The results are exactly the same." << endl;
} else {
cout << "The results differ slightly due to floating-point precision." << endl;
cout << "Difference: " << abs(result1 - result2) << endl;
}

return 0;
}

Trigonometric Functions

6. Write a program to calculate the cosine and tangent of a given angle


cpp

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double angle_degrees;

cout << "Enter angle in degrees: ";


cin >> angle_degrees;

// Convert degrees to radians


double angle_radians = angle_degrees * M_PI / 180.0;

double cosine_value = cos(angle_radians);


double tangent_value = tan(angle_radians);

cout << "Cosine of " << angle_degrees << " degrees = " << cosine_value << endl;
cout << "Tangent of " << angle_degrees << " degrees = " << tangent_value << endl;

return 0;
}

7. Find the inverse sine of 0.5 and print the result in degrees

cpp

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double value = 0.5;

// Calculate inverse sine in radians


double angle_radians = asin(value);

// Convert to degrees
double angle_degrees = angle_radians * 180.0 / M_PI;

cout << "The inverse sine of " << value << " = " << angle_degrees << " degrees" << endl;

return 0;
}
8. Calculate atan2(y, x) for user input and explain the result

cpp

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double x, y;

cout << "Enter x coordinate: ";


cin >> x;
cout << "Enter y coordinate: ";
cin >> y;

double angle_radians = atan2(y, x);


double angle_degrees = angle_radians * 180.0 / M_PI;

cout << "atan2(" << y << ", " << x << ") = " << angle_radians << " radians" << endl;
cout << "In degrees: " << angle_degrees << " degrees" << endl;

cout << "\nExplanation:" << endl;


cout << "atan2(y, x) gives the angle in radians between the positive x-axis" << endl;
cout << "and the point (x, y) in the Cartesian plane." << endl;
cout << "It returns values in the range [-π, π]." << endl;

return 0;
}

Logarithmic and Exponential

9. Find the natural logarithm of a number using log()


cpp

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double num;

cout << "Enter a positive number: ";


cin >> num;

if (num <= 0) {
cout << "Error: Logarithm is defined only for positive numbers!" << endl;
} else {
double result = log(num);
cout << "Natural logarithm of " << num << " = " << result << endl;
}

return 0;
}

10. Find the base-10 logarithm of 100,000

cpp

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double num = 100000.0;

double result = log10(num);

cout << "Base-10 logarithm of " << num << " = " << result << endl;

return 0;
}

11. Use exp(x) to compute e^x and compare it to pow(2.71828, x)


cpp

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

int main() {
double x;

cout << "Enter a value for x: ";


cin >> x;

double e = 2.71828;
double result1 = exp(x);
double result2 = pow(e, x);

cout << fixed << setprecision(10);


cout << "exp(" << x << ") = " << result1 << endl;
cout << "pow(2.71828, " << x << ") = " << result2 << endl;
cout << "Difference: " << abs(result1 - result2) << endl;

return 0;
}

12. Write a program that solves: Compound Interest = P × exp(r × t)


cpp

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double principal, rate, time;

cout << "Enter principal amount (P): ";


cin >> principal;
cout << "Enter annual interest rate (r) in decimal: ";
cin >> rate;
cout << "Enter time in years (t): ";
cin >> time;

double compoundInterest = principal * exp(rate * time);

cout << "Principal: $" << principal << endl;


cout << "Rate: " << (rate * 100) << "%" << endl;
cout << "Time: " << time << " years" << endl;
cout << "Compound Interest (continuous): $" << compoundInterest - principal << endl;
cout << "Final Amount: $" << compoundInterest << endl;

return 0;
}

Rounding and Absolute Value

13. Round a float up using ceil() and down using floor()


cpp

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double num;

cout << "Enter a floating-point number: ";


cin >> num;

double ceilValue = ceil(num);


double floorValue = floor(num);

cout << "Original number: " << num << endl;


cout << "Rounded up (ceil): " << ceilValue << endl;
cout << "Rounded down (floor): " << floorValue << endl;

return 0;
}

14. Use round() to round multiple floating-point numbers and print the results
cpp

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double num1, num2, num3;

cout << "Enter three floating-point numbers:" << endl;


cout << "Number 1: ";
cin >> num1;
cout << "Number 2: ";
cin >> num2;
cout << "Number 3: ";
cin >> num3;

cout << "\nResults after rounding:" << endl;


cout << num1 << " rounded = " << round(num1) << endl;
cout << num2 << " rounded = " << round(num2) << endl;
cout << num3 << " rounded = " << round(num3) << endl;

return 0;
}

15. Take a negative number and display its absolute value

cpp

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double num;

cout << "Enter a negative number: ";


cin >> num;

double absValue = abs(num);

cout << "The absolute value of " << num << " is " << absValue << endl;

return 0;
}
16. Demonstrate the difference between trunc() and floor()

cpp

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double positiveNum, negativeNum;

cout << "Enter a positive decimal number: ";


cin >> positiveNum;
cout << "Enter a negative decimal number: ";
cin >> negativeNum;

cout << "\nFor positive number " << positiveNum << ":" << endl;
cout << "trunc(" << positiveNum << ") = " << trunc(positiveNum) << endl;
cout << "floor(" << positiveNum << ") = " << floor(positiveNum) << endl;

cout << "\nFor negative number " << negativeNum << ":" << endl;
cout << "trunc(" << negativeNum << ") = " << trunc(negativeNum) << endl;
cout << "floor(" << negativeNum << ") = " << floor(negativeNum) << endl;

cout << "\nExplanation:" << endl;


cout << "- trunc() simply removes the decimal part (truncates toward zero)" << endl;
cout << "- floor() rounds down to the nearest integer (toward negative infinity)" << endl;
cout << "For positive numbers, they often give the same result" << endl;
cout << "For negative numbers, they usually give different results" << endl;

return 0;
}

Common questions

Powered by AI

Rounding a floating-point number using `ceil()` and `floor()` provides different results because they aim to round the number to different directions. The `ceil()` function rounds a number upward to the nearest integer, effectively rounding towards positive infinity. This means any fractional component will cause it to round up to the next whole number. Conversely, the `floor()` function rounds the number downward to the nearest integer, rounding toward negative infinity, which means it will round down whenever there is a fractional component .

The `log()` function might be preferred over computing logarithms to arbitrary bases using the `pow()` function due to its optimization and precision. `log()` calculates the natural logarithm (base e), which is fundamental in mathematics and scientific computing, providing high precision and performance. Computing logarithms using `pow()` involves more complex transformations and conversions, which can introduce more floating-point precision errors and inefficiencies. Furthermore, `log()` directly provides the logarithmic result, which is crucial in many scientific and engineering calculations .

Converting an angle from degrees to radians is necessary before using functions like `cos()` and `tan()` because these mathematical functions typically expect the angle input in radians. The radian measure is a natural unit of angular measurement in the context of calculus and mathematical analysis, which these functions are based upon. The conversion ensures compatibility and correctness of results, as there is a direct proportional relationship between angles measured in radians and the arc lengths they subtend on the unit circle .

`atan2(y, x)` is more useful than `atan(y/x)` when determining the angle of a point (x, y) relative to the x-axis. The `atan2()` function takes into account the sign of both arguments to place the result in the correct quadrant, providing results over the range [-π, π]. This helps avoid ambiguities that arise with `atan(y/x)`, such as distinguishing between points in different quadrants or handling division by zero when x=0 .

When comparing floating-point results of `pow()` and `sqrt()` for the same square root computation, potential precision issues may arise due to the slightly different algorithms and internal representations used by these functions. The `sqrt()` function is specifically optimized for square root calculations, minimizing the loss in precision. In contrast, using `pow(x, 0.5)` might lead to minor inaccuracies due to the generalized nature of power calculations, which involve more operations and thus have a greater propensity for introducing rounding errors. Small discrepancies in results may occur, particularly with numbers that are difficult to represent precisely in binary form .

The `pow()` function can be used to compute square roots by raising a number to the power of 0.5, i.e., `pow(x, 0.5)`. However, the `sqrt()` function is specifically optimized for computing square roots and therefore may offer better performance and precision for this specific operation. Both functions should theoretically give the same result, but due to floating-point precision limits, slight differences might occur .

While both `exp(x)` and `pow(2.71828, x)` calculate e^x, using `exp(x)` is generally more accurate and efficient. `exp(x)` is a built-in function specifically optimized to compute the natural exponential function, allowing it to handle very large or very small values with high precision. The use of `pow(2.71828, x)` involves an approximation of e and utilizes the power function, which is less reliable due to floating-point precision errors and inefficiencies in handling powers of irrational numbers. Therefore, slight differences between the two results can occur due to these precision limitations .

The `trunc()` function truncates numbers toward zero by removing the decimal part, which means it gives the same result for both positive and negative numbers that are less than the next integer. In contrast, the `floor()` function rounds down to the nearest integer, which is toward negative infinity. This means for negative numbers, `floor()` returns the next lower integer compared to `trunc()`. For positive numbers, `trunc()` and `floor()` generally give the same result, but for negative numbers, they differ .

The `exp()` function is significant in financial computations where continuous compounding interest is involved. It calculates the exponential function e^x, where `e` is the base of the natural logarithms. In the context of continuous compound interest, the formula `P × exp(r × t)` is used, where `P` is the principal, `r` is the annual interest rate, and `t` is the time in years. This formula allows more accurate calculations of interest, assuming the rate is compounded continuously, which is a more realistic scenario in finance .

The computation of a cube root using `cbrt()` is similar in concept to how square roots are calculated using `sqrt()`. Both functions are specialized to compute their respective roots and are optimized to provide precise results efficiently. The `cbrt()` function directly computes the cube root and generally provides better precision and performance for this specific task compared to using a generic power function like `pow(x, 1.0/3.0)`, which might be less efficient and prone to floating-point errors due to more complex internal calculations and approximations .

You might also like