the usage of the long double - c

The functions purpose is to calculate the square root of a number using the Newton-Raphson method. I included a printf routine in the while loop so I can see the value of root 2 get closer and closer to the actual value. I originally used float to define epsilon but as I increased the value of epsilon, the value of the return results seem to be cut-off after a certain number of digits. So I decided to switch all the variable to long double, and the program is displaying negative results. How do I fix it?
//Function to calculate the absolute value of a number
#include <stdio.h>
long double absoluteValue (long double x)
{
if (x < 0)
x = -x;
return (x);
}
//Function to compute the square root of a number
long double squareRoot (long double x, long double a)
{
long double guess = 1.0;
while ( absoluteValue (guess * guess - x) >= a){
guess = (x / guess + guess) / 2.0;
printf ("%Lf\n ", guess);
}
return guess;
}
int main (void)
{
long double epsilon = 0.0000000000000001;
printf ("\nsquareRoot (2.0) = %Lf\n\n\n\n", squareRoot (2.0, epsilon));
printf ("\nsquareRoot (144.0) = %Lf\n\n\n\n", squareRoot (144.0, epsilon));
printf ("\nsquareRoot (17.5) = %Lf\n", squareRoot (17.5, epsilon));
return 0;
}

If you are using the version of Code::Blocks with mingw, see this answer: Conversion specifier of long double in C
mingw ... printf does not support the 'long double' type.
Some more supporting documentation for it.
http://bytes.com/topic/c/answers/135253-printing-long-double-type-via-printf-mingw-g-3-2-3-a
If you went straight from float to long double, you may try just using double instead, which is twice as long as a float to start with, and you may not need to go all the way to a long double.
For that you would use the print specifier of %lf, and your loop might want to look something like this, to prevent infinite loops based on your epsilon:
double squareRoot ( double x, double a)
{
double nextGuess = 1.0;
double lastGuess = 0.0;
while ( absoluteValue (nextGuess * nextGuess - x) >= a && nextGuess != lastGuess){
lastGuess = nextGuess;
nextGuess = (x / lastGuess + lastGuess) / 2.0;
printf ("%lf\n ", nextGuess);
}
return nextGuess;
}

Related

C GMP Non-Integer Powers

I am using the C GMP library, and I am trying to calculate a float with the mpf_t type raised to the power 1.0 / n where n is an int. However, it seems that the pow function for this type only takes integer inputs for the power. Is there a function in this library that can do powers in the form of doubles, and if not, is there a fast algorithm I can make use of instead?
Is there a function in this library that can do powers in the form of
doubles,
No.
and if not, is there a fast algorithm I can make use of instead?
Yes.
The x to power 1.0/n is the same as square n root of x. And there is an efficient algorithm to calculate that see: nth root algorithm - Wikipedia
This is working C code which you can easily adapt for GMP.
Function:
void mpf_pow_ui (mpf_t rop, const mpf_t op1, unsigned long int op2);
- set rop to op1 raised to the power op2, can be used in place of dexp.
#include <stdlib.h>
#include <stdio.h>
double dexp(double a, double toN){
double ret = 1;
for(int i = 0; i< toN; ++i)
ret *= a;
return ret;
}
double nth_root(double num, int N, double precision){
double x;
double dx;
double eps = precision;
double A = num;
double n = N;
x = A * 0.5;
dx = (A/dexp(x,n-1)-x)/n;
while(dx >= eps || dx <= -eps){
x = x + dx;
dx = (A/dexp(x,n-1)-x)/n;
}
return x;
}
int main()
{
int N = 4;
int A = 81.0;
double nthRootValue = nth_root(A, N, 10e-8);
printf("Nth root is %lf", nthRootValue);
return 0;
}
Test:
Nth root is 3.000000

numerical integration using a pointer to a function always return 0

I am trying to use the function that I was given by my professor to calculate the integral of a polynomial function (polynomial such as: ax^2+bx+c). the function is:
double numbericalIntegration(double a ,double b ,double(*func)(double)){
double delta = (b - a)/32;
double sum=0, x;
for(x= a+0.5*delta; x<b ; x+=delta)
{
sum+=(*func)(x);
}
return sum*delta;
}
I changed a lot in order to integrate a polynomial function. but I was get the answer 0. why is that? and I'd appreciate if anybody tried to correct my work. my code is:
double integralPoly(double x, double a, double b, double c){
return (a*pow(x,3))/3 +(b*pow(x,2))/2 + (c*x);
}
double numbericalIntegration(double a ,double b ,double(*func)(double,double,double,double), double firstNum, double secondNum, double thirdNum){
double delta = (b - a)/32;
double sum=0, x;
for(x= a+0.5*delta; x<b ; x+=delta)
{
sum+=(*func)(x, firstNum, secondNum, thirdNum);
}
return sum*delta;
}
int main()
{
double (*func)(double,double,double,double);
func = integralPoly;
double sum = numbericalIntegration(2,4,func,1,1,4);
printf("sum = %d",sum);
return 0;
}
You need to change two things. First your polynomial function doesn't make any sense. You said it needs to be in the form of ax^2+bx+c but in your code polynomial is (ax^3)/3+(bx^2)/2+c*x. Your function should be:
double integralPoly(double x, double a, double b, double c){
return (a*pow(x,2)) +(b*x) + c;
}
Also you need to change your printf. %d is integer type specifier and you need double, so you need to use %f for example:
printf("sum = %f",sum);
Now the output of your program is:
sum = 32.666016
which is correct for your parameters.

C Program to Calculate Hypotenuse

I'm fairly new to coding and am currently learning C. In class I was given an assignment to write a program that calculates the hypotenuse of the triangle by using our own functions. However, there seems to be something wrong with the code that I have written.
#include <stdio.h>
#include <math.h>
double hypotenuse(double x, double y, double z);
int main(void) {
double side1, side2, side3, counter;
side3 = 1;
for (counter = 0; counter <= 2; counter++) {
printf("Enter values for two sides: ");
scanf_s("%d %d", &side1, &side2);
printf("%.2f\n", hypotenuse(side1, side2, side3));
}
return 0;
}
double hypotenuse(double x, double y, double z) {
x *= x;
y *= y;
z = sqrt(x + y);
return z;
}
My instructor said that we're allowed to use the square root function sqrt of the math library. The main errors that I'm facing are:
1) side3 is not defined (This is why I just arbitrarily set it to 1, but is there some other way to prevent this error from happening?)
2) If I, for example, inputted 3 and 4 as side1 and side2, then side3 should be 5. However, the printed result is an absurdly long number.
Thank you for the help! Any words of advice are appreciated.
You don't need side3 variable - it is not used in calculation. And you function hypotenuse returns the result, so you can directly output the result of sqrt.
I use Ubuntu Linux and write it this way. Please look if you like it.
#include <stdio.h>
#include <math.h>
double hypotenuse(double x, double y) {
double z = sqrt(x * x + y * y);
return z;
}
int main(void) {
double b1, b2, counter;
for (counter = 0; counter <= 2; counter++) {
printf("Enter values for two sides: ");
scanf("%lf %lf", &b1, &b2);
printf("%.2f\n", hypotenuse(b1, b2));
}
return 0;
}
Test
$ ./a.out
Enter values for two sides: 1 1.73
2.00
OP's code has some problems:
Key problem: Code should have generated a compiler warning as scanf() is directed to treat &side1 as an int *. Turn on all compiler warnings to save you time. Code used "%d" rather than the matching "%lf" to read a double. Also the return value should be checked to validate input.
double side1, side2, side3, counter;
...
// scanf_s("%d %d", &side1, &side2);
if (scanf_s("%lf %lf", &side1, &side2) != 2) puts("Input error");
size3 is not needed. Call hypotenuse() with 2 arguments. #ghostprgmr
// printf("%.2f\n", hypotenuse(side1, side2, side3));
printf("%.2f\n", hypotenuse(side1, side2));
// double hypotenuse(double x, double y, double z) {
double hypotenuse(double x, double y) {
double z = ...
Minor: Code used "%.2f" to print the value of the hypotenuse. This may be OK with select input values to OP's code, but is a poor choice, in general. If input values are vary small like 0.001 and 0.002, the output will print rounded value of 0.00. With very large values, the result will show many non-important digits as OP found with 130899030500194208680850288727868915862901750748094271410143‌​232.00.
For development and debugging, consider using "%e" ,"%g" or "%a" to see a relevant double.
Note that x * x + y * y is prone to over/under flow, even when mathematically sqrt(x * x + y * y) is in the double range. That is one advantage of the standard function hypot(x,y) as it usually handles those edge cases well.
As a reference for anyone viewing this question:
You don't need to write your own function. Standard C provides functions to calculate the hypotnuse:
7.12.7.3 The hypot functions
Synopsis
#include <math.h>
double hypot(double x, double y);
float hypotf(float x, float y);
long double hypotl(long double x, long double y);
Note that you likely need to link with -lm, though that's not listed explicitly in the function documentation in the C standard nor the latest POSIX documentation. It might be documented elsewhere in the standards.
(Link to C11 [draft] standard - likely to be much longer-lived.)
Use correct format specifiers!
Format Specifier for double is not %d! Rest is fine.
#include <stdio.h>
#include <math.h>
double hypotenuse(double x, double y, double z);
int main(void) {
double side1, side2, side3, counter;
side3 = 1;
for (counter = 0; counter <= 2; counter++) {
printf("Enter values for two sides: ");
scanf("%lf %lf", &side1, &side2);
printf("%.2f\n", hypotenuse(side1, side2, side3));
}
return 0;
}
double hypotenuse(double x, double y, double z) {
x *= x;
y *= y;
z = sqrt(x + y);
return z;
}
Also you could modify it to this:
#include <stdio.h>
#include <math.h>
double hypotenuse(double x, double y);
int main(void) {
double side1, side2, counter;
for (counter = 0; counter <= 2; counter++) {
printf("Enter values for two sides: ");
scanf("%lf %lf", &side1, &side2);
printf("%.2f\n", hypotenuse(side1, side2));
}
return 0;
}
double hypotenuse(double x, double y) {
x *= x;
y *= y;
return sqrt(x + y);
}

Calculation the Taylor series of sinh

The function calculates the value of sinh(x) using the following
development in a Taylor series:
I want to calculate the value of sinh(3) = 10.01787, but the function outputs 9. I also get this warning:
1>main.c(24): warning C4244: 'function': conversion from 'double' to 'int', possible loss of data
This is my code:
int fattoriale(int n)
{
int risultato = 1;
if (n == 0)
{
return 1;
}
for (int i = 1; i < n + 1; i++)
{
risultato = risultato * i;
}
return risultato;
}
int esponenziale(int base, int esponente)
{
int risultato = 1;
for (int i = 0; i < esponente; i++)
{
risultato = risultato * base;
}
return risultato;
}
double seno_iperbolico(double x)
{
double risultato = 0, check = -1;
for (int n = 0; check != risultato; n++)
{
check = risultato;
risultato = risultato + (((esponenziale(x, ((2 * n) + 1))) / (fattoriale((2 * n) + 1))));
}
return risultato;
}
int main(void)
{
double numero = 1;
double risultato = seno_iperbolico(numero);
}
Please help me fix this program.
It is actually pretty great that the compiler is warning you about this kind of data loss.
You see, when you call this:
esponenziale(x, ((2 * n) + 1))
You essentially lose your accuracy since you are converting your double, which is x, to an int. This is since the signature of esponenziale is int esponenziale(int base, int esponente).
Change it to double esponenziale(double base, int esponente), risultato should be a double as well, since you are returning it from the function and performing mathematical operations with/on it.
Remember that dividing a double with an int gives you a double back.
Edit: According to ringø's comment, and seeing how it actually solved your issue, you should also set double fattoriale(int n) and inside that double risultato = 1;.
You are losing precision since many of the terms will be fractional quantities. Using an int will clobber the decimal portion. Replace your int types with double types as appropriate.
Your factorial function will overflow for surprisingly small values of n. For 16 bit int, the largest value of n is 7, for 32 bit it's 12 and for 64 bit it's 19. The behaviour on overflowing a signed integral type is undefined. You could use unsigned long long or a uint128_t if your compiler supports it. That will buy you a bit more time. But given you're converting to a double anyway, you may as well use a double from the get-go. Note that an IEEE764 floating point double will hit infinity at 171!
Be assured that the radius of convergence of the Maclaurin expansion of sinh is infinite for any value of x. So any value of x will work, although convergence might be slow. See http://math.cmu.edu/~bkell/21122-2011f/sinh-maclaurin.pdf.

-1.#IND00 output for certain input values

I'm trying to write a code that will take x as input and give cos(x) as output, using maclaurin's series.I'm using a while loop until the difference of two consecutive results is less then 0.001. I'm using double type to accomodate larger values.
the code works when x is in range [-2,2], but if x is greater or less than this range the ouput is -1.#IND00. Why is it happening? is the output value out of range ? how can i fix this ??
my code is :
#include <stdio.h>
double abs(double a);
double power(double p, int q);
int fact(int a);
int main()
{
int i=1,j=2*i;
double x,s=1.0,p,l=0.001;
printf("Enter x: ");
scanf("%lf", &x);
p = s+ power(-1,i) * power(x,j) / fact(j);
while (abs(p-s)>l){
i++; j=2*i;
s=p;
p = s+ power(-1,i) * power(x,j) / fact(j);
}
printf("cos(%f) = %f", x,p);
return 0;
}
double abs(double a)
{
if (a>=0) return a;
else return (-a);
}
double power(double p, int q)
{
int i;
double a=1.0;
for (i=0; i<q; i++){
a=a*p;
}
return a;
}
int fact(int a)
{
int i,p=1;
if (a==0 || a==1) return 1;
else
while (a!=1){
p=p*a;
a--;
}
return p;
}
update your scanf function to
scanf("%lf", &x);
Also you need to check pow and fact, these functions could overflow. Especially, fact which only use int.
As a larger |x| is use, more terms are needed and fact() overflows and strange results follow. Use double.
// int fact(int a)
double myfact(double p, int q) {
int i;
double a = 1.0;
for (i=0; i<q; i++){
a=a*p;
}
return a;
}
Eventually with values somewhere larger |x| > 30, other limitations kick in using this method. The limitation is due to precision and not range. For large values a significantly different algorithm should be used.
Potential conflict between int abs(int j) in <stdlib.h>. The prototyped may be found via stdio.h and conflicts with OP double abs(double a). In any case, abs() is a standard library function and OP should avoid that function name. Also recommend renaming power().
// double abs(double a)
double myabs(double a)

Resources