My program uses genetic techniques to build equations.
It randomly assembles strings into an equation with one unknown.
"(((x + 1) * x) / (4 * 6) ** 2)"
One of the strings is: "math.factorial(random.randint(1,9))"
So an equation is typically something like:
"(((x + 1) * x) / (4 * 6) ** 2) + math.factorial(random.randint(1,9))
"
Fifty different equations are generated and then assigned a fitness value according to
how well they approximate the sin function over a range of values.
for x in numpy.arange(1,6.4,.1):
fitness += abs(eval"(((x + 1) * x) / (4 * 6) ** 2) + math.factorial(random.randint(1,9)) - numpy.sin(x))")
The program often throws an exception which is caught by an 'except TypeError' clause. The error message is "unsupported operand types for +:'long' and 'numpy.float64'"
When I try "type(numpy.sin(1))"it returns
type: numpy.float64
How do I get 'long' and 'numpy.float64' operand types to work together? Any help would be appreciated.
@catchmeifyoutry: good idea! Unfortunately it's a heck of an equation. I've never
tried to take one this long apart. I have wondered if there is a parsing utility to help
resolve all the bracket开发者_StackOverflow社区s.
(((math.factorial(random.randint(1,9))))-(((x)+((((math.factorial(random.randint(1,9))))**((math.factorial(random.randint(1,9)))))-(((6.0)/(((8.0)/(((3.0)-(8.0))/(((5.0)*((2.0)/(x)))/(8.0))))+(4.0)))/(8.0))))+(7.0)))
I'll try to catch the value of x at which it failed.
First, you are missing a closing bracket in your example, and the (+ or - or / or * or **)
is confusing.
What are you trying to achieve? Do you just want to insert the result in the string? Try this:
for x in numpy.arange(1,6.4,.1):
s = "sinus %f is %f!" % (x, numpy.sin(x))
print type(s), s
See string formatting documentation.
EDIT
Ah yes, genetic programming, that explains what you're trying to do ;)
Based on your updated information, I have to guess that your string construction is sometimes faulty somehow. Change your code to display the string that causes the exception to be thrown. Easiest way is to just print the string before calling eval on it, and when the exception is thrown you can see what the last equation was. Then, if it is not clear what is wrong with it, you can post that equation here.
This works for me:
for x in numpy.arange(1,6.4,.1):
eval("( 1 + (2 * 3) / 4 ) * numpy.sin(x)")
精彩评论