-4

how can I get absolute value for the double diff in this case?

double cos_delta(double x, double delta)
 {
int n = 1;   // n should start with 1 because it is the number of terms

double diff = cos_N(x, n ) - cos_N(x, n - 1);  // n and n-1 instead of n-1 and n-2

********* here ************

while (diff > delta) { // fabs returns absolute value of a double

    n++;
    diff = cos_N(x, n ) - cos_N(x, n - 1);
}
printf("n = %d\n", n);
return cos_N(x, n);

}

Joshua
  • 40,822
  • 8
  • 72
  • 132
Saeed
  • 1
  • 3
  • Why without using `math.h`? – user2736738 Nov 25 '17 at 05:09
  • because i'm not able to use it in this program – Saeed Nov 25 '17 at 05:10
  • this is not a question, answer is too easy to ask here: `double abs(double i) { return i < 0? -i: i; }` – MewX Nov 25 '17 at 05:19
  • but in C, as far as I know, you can't use a faction within a function! I know these kinda questions are easy for you guys, but i'm trying to learn – Saeed Nov 25 '17 at 05:23
  • 3
    Huh? What do you mean by "can't use a faction within a function"? And how is that relevant to your question? – Peter Nov 25 '17 at 05:28
  • What do you mean by "can't use a function within a function"? You shouldn't define functions within other functions, though GCC allows it as an extension. You can call other functions from within a function though. And creating a simple `static inline double abs_dbl(double x) { return (x < 0.0) ? -x : x); }` seems pretty straight-forward. (Note that `abs()` is an integer function defined in ``; it's why the standard function for `double` is `fabs()` and not `abs()` — we don't have `fcos()` (though there is `cosf()`, but that's a separate discussion.) – Jonathan Leffler Nov 25 '17 at 05:30
  • why are you not able to use it? If there's no math.h that's not a C compiler. If you use gcc [you must specify `-lm`](https://stackoverflow.com/q/4606301/995714) – phuclv Aug 26 '18 at 02:55

1 Answers1

2

You can do the comparison and put the result (In case of negative double value prepend it with unary - (unary minus) else the value is positive).

Using a simple if statement will be best way to deal with this.

if( dblVal < 0 )
   dblVal =  -dblval;

or you can make a function and use it like this

double myabs(double d){
    if( d < 0 )
      return -d;
    return d;
}

But it is always better to use the math library functions fabs() etc.

user2736738
  • 30,591
  • 5
  • 42
  • 56
  • 2
    If this is what I think I'm looking at he'll get link errors calling `fabs()`. If he's building up a `cos()` power series the hard way he obviously can't call `cos()` so I don't think `fabs()` is there either. On the other hand you did answer his question quite well. – Joshua Aug 26 '18 at 02:17
  • @Joshua.: Thanks for passing by and reading the answer. Anu suggestions or edit in the answer is highly appreciated. Thanks. – user2736738 Aug 26 '18 at 16:10