8

How do I make a program that asks for one floating point number in Python and then calculates the absolute value? I've already tried the asking, but I can't make the line where it calculates the absolute value.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
K.Kane
  • 115
  • 1
  • 1
  • 2

1 Answers1

25

You can do it with the built-in abs() function:

absolute_val = abs(x)

Otherwise, without the built-in function, use math:

absolute_val = (x ** 2) ** 0.5
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 7
    `x if x >= 0 else -x`. Using squaring and square root on a floating point number is probably both slower and more likely to give an inaccurate answer because of precision. – zstewart Sep 12 '15 at 15:16
  • I've doing some quick tests, and I haven't actually found a value where `(x**2)**5 != abs(x)`, so I guess that's usable, but using floating point operations where a simple if/else can solve your problem seems like a bad idea to me. – zstewart Sep 12 '15 at 15:23
  • 2
    @zstewart What about the `abs()` function? That one's probably reliable. The other one I just added as a "fun fact" I guess. –  Sep 12 '15 at 15:29
  • What do you mean what about `abs`? Of course `abs` is reliable, its a builtin, that's what it does. The tests I did were something like this: `all(((x**2)**0.5) == abs(x) for x in np.arange(-1954799126841, -1954799126851, -0.0001))` – zstewart Sep 12 '15 at 16:19