user2817017
user2817017

Reputation: 139

Simple function using numpy won't run

I have been at this for more than 2 hours. Each individual line prints out the result I am looking for. However, when I run all the lines in the program, python print values or Ixx, Iyy and Ixy. Why is this?

import numpy as np

Ixx = 14600000
Iyy = 14600000
Ixy = 7080*(47.2-12.5)**2
alpha = 45

x = 0.5*(Ixx+Iyy)+0.5*(Ixx-Iyy)*np.cos(2*alpha/180*np.pi)+Ixy*np.sin(2*alpha/180*np.pi)
y = 0.5*(Ixx+Iyy)-0.5*(Ixx-Iyy)*np.cos(2*alpha/180*np.pi)-Ixy*np.sin(2*alpha/180*np.pi)
z = 0.5*(Ixx-Iyy)*np.sin(2*alpha/180*np.pi)+Ixy*np.cos(2*alpha/180*np.pi)

print x,y,z

Upvotes: 0

Views: 92

Answers (2)

user2817017
user2817017

Reputation: 139

I can't say I understand why, but changing the interior of my sinus and cosinus terms solved the problem. I changed

x = 0.5*(Ixx+Iyy)+0.5*(Ixx-Iyy)*np.cos(2*alpha/180*np.pi)+Ixy*np.sin(2*alpha/180*np.pi)
y = 0.5*(Ixx+Iyy)-0.5*(Ixx-Iyy)*np.cos(2*alpha/180*np.pi)-Ixy*np.sin(2*alpha/180*np.pi)
z = 0.5*(Ixx-Iyy)*np.sin(2*alpha/180*np.pi)+Ixy*np.cos(2*alpha/180*np.pi)

to

Ixx_a = 0.5*(Ixx+Iyy)+0.5*(Ixx-Iyy)*np.cos(np.pi*alpha/90) + Ixy*np.sin(np.pi*alpha/90)
Iyy_a = 0.5*(Ixx+Iyy)-0.5*(Ixx-Iyy)*np.cos(np.pi*alpha/90) - Ixy*np.sin(np.pi*alpha/90)
Ixy_a = 0.5*(Ixx-Iyy)*np.sin(np.pi*alpha/90)+Ixy*np.cos(np.pi*alpha/90)

which is mathematically equivalent, but apparently numpy finds it easier to compute.

Upvotes: 0

Peter Gibson
Peter Gibson

Reputation: 19564

If you're running this under python2.x, then you are losing information with the statement 2*alpha/180*np.pi (python3.x should work though).

The operations are evaluated in order of precedence (left to right in this case), which gives

((2 * alpha) / 180) * ni.pi
=> (90 / 180) * ni.pi # integer division truncates this to 0
=> 0 * ni.pi

You need to manually convert to a float, either:

np.sin(2.0*alpha/180*np.pi) # the floating point 2.0 will promote alpha to float for the multiply

Or

np.sin(2*float(alpha)/180*np.pi) # explicit, very clear

Or

alpha = 45.0 # this is a little dangerous as you might change the angle in the future and forget to make it a float again

Upvotes: 4

Related Questions