Python Converting Python to C: Struggling With Code

  • Thread starter Thread starter swartzism
  • Start date Start date
Click For Summary
The discussion revolves around converting Python code to C, specifically handling the `acos()` function and its error management. Participants emphasize that C lacks the `try...catch` mechanism found in Python, suggesting that pre-validation of the input argument is crucial to avoid errors when calling `acos()`. The correct input for `acos()` should be within the range of [-1, 1], and checks should be performed before invoking the function to ensure safety. Additionally, there is confusion regarding Python's handling of `None` values in function arguments, with participants clarifying that the logic in the provided code snippet may lead to unintended behavior. Overall, the conversation highlights the importance of understanding language-specific functions and error handling when converting code.
swartzism
Messages
103
Reaction score
0
I'm in the process of converting some Python code to C and have come across a structure I'm not sure on how to translate:

(This is a hybrid of the two languages)
Code:
   try:
      return(acos(ang)*RAD_2_DEG);
   except ValueError:
      if (ang < -1.0)
         return(180.0);
      else
         return(0.0);

Does anyone know how to get this fully to C? It is trying to return acos(ang)*RAD_2_DEG and if it catches ValueError, it then checks if ang is less than -1.0 and returns a value of 180 or 0 based on that. Any help would be appreciated.

Thanks in advance.
 
Technology news on Phys.org
Hhhmmm...I am not C expert, but just don't try to convert the code literally, line by line, just go for the overall objective.

what I am saying, it's that maybe you should start by doing the validation of ang, in the first place; if it meets the "failing" criteria, you take the shortcut to return something, if it passes the tests and it is then safe to use acos() on it, then you do that last
 
Roger that. I found a similar snippet of code that was doing the same thing, but much more clearly. I got it converted successfully. Thanks for the tip though.
 
IIRC, C doesn't have try...catch blocks, although C++ and C# do.

As gsal suggested, rather than completely duplicate the code you have, just do the checks before you call acos().

BTW, the argument to acos() is not an angle - it's a number in the interval [-1, 1]. If the argument is not in this interval, you should not call acos(); otherwise an error will be produced.

The result from acos() is an angle in radians (which I believe you already know).
 
In the original Python, The acos() function will throw a "value error" if its argument is > 1 or < -1. If that happens, you do what is in the "except" part. Otherwise, what you "try" to do will be successful.

As gsal said, the easiest way to do this in C is test the argument yourself before you call acos().

The standard C library does have some very primitive error-catching capabilities, but the details are implementation dependent, so it's usually easier to code your own checks rather than try to use them.

The C++ language has "try" and "catch" which works in a similar way to Python.
 
Guys,

Thank you for the input. I did not think of the nature of acos() being between [-1,1], that is very helpful. I have come across something that baffles me in the same arena:

Code:
    def update_coordinates(self, start=None, end=None, ztox=Atom3d.ztox):

       // Compute cartesian coordinates from internal coordinates
       // 
       // Arguments
       // 
       //    o *start* - integer 
       // 
       //    o *end* - integer 
        
        if start == end == None:
            ztox(self.atoms)
        else:
            if start is None: start = 3
            if end is None: end = self.num_atoms
            ztox(self.atoms, start, end)

This seems to input start and end as None, check whether they are None in an if-else statement where both if and else are satisfied since start and end are read in as None. Am I missing something?

Again, thank you for the help.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

Replies
1
Views
2K
Replies
5
Views
15K
  • · Replies 4 ·
Replies
4
Views
5K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
1K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 1 ·
Replies
1
Views
4K
  • · Replies 1 ·
Replies
1
Views
2K
Replies
9
Views
3K