4 ms·
Show HN: A terrible way to calculate absolute value in Python
- sonicrocketman 5y agoFor anyone who's able to, I'd love to hear how my awful method compares with other real methods. (i.e. not accounting for some mathematical nuance, performance, etc)
- smoldesu 5y agoI mean, most of the reason why this works is because Python doesn't care about type safety in the slightest. There's a reason why more strongly-typed languages would outright disallow a program like this: it's not only unsafe, it's outright incorrect. The ASCII symbol for '-' is not a suitable analog for our concept of 'negative'
- upbeat_general 5y agoYou could certainly do this in languages with stronger type safety. All it relies on is checking the type and toString/fromString conversations.
- D13Fd 5y ago> The ASCII symbol for '-' is not a suitable analog for our concept of 'negative' Why not?
- smoldesu 5y agoConventional computing has no concept of positive or negative, but rather uses a signing bit to discern their polarity (for example, an 8-bit value could represent either -127-128 or 0-255). That concept of "type correctness" is lost whenever you haphazardly cast unlike values between one another (in this case ints and strings), so we're trusting the Python interpreter to magically perform this illegal, slow operation without supervision.
- gus_massa 5y agoI've seen similar code to calculate the last digit of a number. It's much slower than %.
- sudobash1 5y agoIn addition to the obvious issues, this method ignores python's __abs__: https://docs.python.org/3/reference/datamodel.html#object.__abs__ https://docs.python.org/3/reference/datamodel.html#object.__... You can make you own "numeric" types in python by implementing the proper methods in your numeric class.
- D13Fd 5y agoI don't know why you are getting downvoted. I jumped into the comments, eager to see an explanation of exactly why this is horrible, and was disappointed.
- deleted 5y ago[deleted]
- Vanit 5y agoI've never used Python, but if there's an issue here it's probably because the value has to traverse through being a string and any opinions in the to/from string conversions could cause unexpected mutations to floats?