I am not a strong Python programmer, and do not know the proper way to tackle a problem I have run into. I am attempting to replicate a process defined by others and cannot deviate from that process. I am calculating values for a field in an attribute table (Field5) which is derived from other fields in the table using a given formula.
Here is a simplified version of the formula:
Field5 = math.log(!Field1! / !Field2!) + math.log(!Field3! / !Field4!)
ERROR 000539: Traceback (most recent call last):
File "<expression>", line 1, in <module>
ValueError: math domain error
Solved! Go to Solution.
Then, I think you should check field1/2 and field3/4 separately this way:
import math
def calculate_field5(field1, field2, field3, field4):
exp1 = field1 / field2
exp2 = field3 / field4
try:
exp1 = math.log(exp1)
except ValueError:
exp1 = 0
try:
exp2 = math.log(exp2)
except ValueError:
exp2 = 0
return exp1 + exp2
Hope that helps!
Hello @BeckHag,
You can accomplish your goal using the code block:
import math
def calculate_field5(field1, field2, field3, field4):
try:
return math.log(field1 / field2) + math.log(field3 / field4)
except ValueError:
return 0
Regards,
Thank you, that almost gets me there. Is there a way to set it up so that the term rather than Field5 is given a value of zero? For instance, suppose the following values applied:
Field1 = 2, Field2 = 3, Field3 = 0, Field4 =3
Applying these to the formula we get:
Field5 = math.log(!Field1! / !Field2!) + math.log(!Field3! / !Field4!)
Field5 = math.log(2 / 3) + math.log(0 / 3)
I want this to reduce to: Field5 = -0.40547 + 0
Thank you again for your help with this.
Then, I think you should check field1/2 and field3/4 separately this way:
import math
def calculate_field5(field1, field2, field3, field4):
exp1 = field1 / field2
exp2 = field3 / field4
try:
exp1 = math.log(exp1)
except ValueError:
exp1 = 0
try:
exp2 = math.log(exp2)
except ValueError:
exp2 = 0
return exp1 + exp2
Hope that helps!