Skip to content
Advertisement

sqrt() c++ and math.sqrt() python

i am new at python and i had this precision problem with python which i did not have before with c++, the code is for python

JavaScript

the result is

JavaScript

for c++

JavaScript

the result is

JavaScript

this can make crashes

Advertisement

Answer

Different programming languages may behave differently when it comes to float arithmetics. It may come to optimisations, internal implementations of functions like acos etc.

First, notice that in C++, acos returns the special value nan for values out of range, while in Python it throws the ValueError exception. You can, however, easily get the C++ behavior like this:

JavaScript

Furthermore, you can add rounding to accept values slightly out of range. Your number has 15 zeroes after the decimal point, so let’s round to 15 places (for the sake of demonstration):

JavaScript

With this modification, your code will produce the results you expect.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement