Converting Python to C: Struggling With Code

  • Context: Python 
  • Thread starter Thread starter swartzism
  • Start date Start date
Click For Summary

Discussion Overview

The discussion revolves around converting Python code to C, focusing on error handling and function argument validation, particularly with the acos() function. Participants explore how to effectively translate Python's exception handling into C's error-checking mechanisms.

Discussion Character

  • Technical explanation
  • Conceptual clarification
  • Debate/contested

Main Points Raised

  • One participant presents a Python code snippet using try...except for handling errors with the acos() function and seeks guidance on translating it to C.
  • Another participant suggests validating the input argument before calling acos() instead of trying to replicate the Python error handling directly.
  • A different participant notes that C does not support try...catch blocks, unlike C++ and C#, and emphasizes the importance of checking the argument range for acos().
  • It is mentioned that the argument for acos() must be within the interval [-1, 1], and calling it outside this range will produce an error.
  • Further clarification is provided about the nature of error handling in C, indicating that it is often easier to implement custom checks rather than relying on standard library error-catching capabilities.
  • A new participant introduces a separate Python code snippet involving None checks and questions the logic behind the if-else structure, seeking clarification on its behavior.

Areas of Agreement / Disagreement

Participants generally agree on the need for input validation before calling acos() in C. However, there is no consensus on the best approach to handle the translation of Python's exception handling into C, and the discussion remains open regarding the logic of the second code snippet involving None checks.

Contextual Notes

Participants note that the behavior of acos() and its requirements for input are crucial for successful translation, highlighting the differences in error handling between Python and C. The discussion also reflects on the potential pitfalls of directly translating code without considering language-specific features.

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.
 

Similar threads

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