In Mathematica, I try to export a list into python format as follows, but failed:

```
In[106]:= getSGLatt[#]&/@Range[157,158];
(BasicVectors[#]/.{a->1,b->1,c->1, \[Alpha]->Pi/2,\[Beta]->Pi/2,\[Gamma]->Pi/2} // Transpose)&/@%
ExportString[%,"PythonExpression"]
Out[107]= {{{0, Sqrt[3]/2, 0}, {-1, 1/2, 0}, {0, 0, 1}}, {{0, Sqrt[3]/
2, 0}, {-1, 1/2, 0}, {0, 0, 1}}}
During evaluation of In[106]:= Export::invalidpythonexpr: The expression Sqrt[3]/2 could not be encoded as a Python literal expression.
Out[108]= $Failed
```

How to fix this problem?

See here for the related discussion.

Regards,

Zhao

python does not have the same support for symbolic math that Mathematica does, and so `Sqrt[3]/2`

isn’t valid syntax, just like the error says. It seems like a problem with the code doing the exporting.

A python expression that corresponds to that value (up to floating point error) would be `3 ** 0.5 / 2`

. Alternatively, there are tools like SymPy.

So, how can I express such numbers in python precisely?

I edited my post to give a little more information. If you want exact mathematical values, SymPy might be the right choice. If you want to calculate the floating-point approximation, you can use `math.sqrt(3)`

or `3 ** 0.5`

.

If you want to do a whole lot of numeric calculation I would reach for numpy

Thank you for your comprehensive explanation.

At the moment, one of the problems I’m having is that I’m doing some group theory calculations based on python that involve both exact numbers and floating-point numbers, which sometimes causes cumulative errors that lead to wrong results, as described in the problem discussed here, and I don’t know how to handle this gracefully and reasonably.

Yeah I don’t either it is always going to be difficult to perform very accurate calculations with floating-point numbers. Higher-precision floating point might help , or a symbolic math library, but both come at the cost of performance.

There are sometimes some strategies one can use to minimize the accumulation of the errors–re-ordering the evaluation of the result to retain precision as long as you can–but that is dependent on the calculation you’re doing.

1 Like