c - the usage of the long double -


the functions purpose calculate square root of number using newton-raphson method. included printf routine in while loop can see value of root 2 closer , closer actual value. used float define epsilon increased value of epsilon, value of return results seem cut-off after number of digits. decided switch variable long double, , program displaying negative results. how fix it?

//function calculate absolute value of number  #include <stdio.h>  long double absolutevalue (long double x) {     if (x < 0)         x = -x;     return (x); }  //function compute square root of 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 using version of code::blocks mingw, see answer: conversion specifier of long double in c

mingw ... printf not support 'long double' type.

some more supporting documentation it.

http://bytes.com/topic/c/answers/135253-printing-long-double-type-via-printf-mingw-g-3-2-3-a

if went straight float long double, may try using double instead, twice long float start with, , may not need go way long double.

for use print specifier of %lf, , loop might want this, prevent infinite loops based on epsilon:

double squareroot (    double x,     double a) {     double nextguess = 1.0;     double lastguess = 0.0;      while ( absolutevalue (nextguess * nextguess - x) >= && nextguess != lastguess){         lastguess = nextguess;         nextguess = (x / lastguess + lastguess) / 2.0;         printf ("%lf\n ", nextguess);         }      return nextguess; } 

Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -