-9

我一直在尝试为这个函数编写代码,但我无法asin在 python 2.7 中工作。任何想法为什么?

import math
from decimal import *

def main():
    H = raw_input ("Please enter hight:")
    H = int(float(H))
    m = raw_input ("Please enter crest thickness:")
    m = int(float(m))
    n = raw_input ("Please enter base thikness:")
    n = int(float(n))

    Fx = 0.0
    Fy = 0.0
    Magnitude = 0.0
    Direction = 0.0

p = 1000 #dencity
g = 9.81 #gravity

R = math.sqrt(H*H + n*n)
#Force in x direction
Fx = (-p*g*m*(H*H))/2.0
#Force in y direction
Fy = -p*g*R*(((math.asin(n/H))/2.0)-sin((2*math.asin(n/H))/4.0))

#Overall force
Direction = math.atan(Fy/Fx)
Magnitude = sqrt(Fx*Fy + Fy*Fy)

print ("The force magnitude is", Magnitude)
print ("The force direction is", Direction)
4

2 回答 2

1

在 3.0 之前的 Python 中,将整数除以整数(就像你对n/Hinside所做的那样math.asin(n/H))返回一个整数(这是除法结果的下限值)。您必须将至少一个操作数转换为float或在 Python 源文件的开头声明

from __future__ import division

阅读http://python.org/dev/peps/pep-0238了解详情

于 2013-09-27T14:19:19.290 回答
0

代码更正

有几个问题:

  1. 没有内置的sin,需要从mathas使用math.sin

    ---> 23 Fy = -p*g*R*(((math.asin(n/H))/2.0)-sin((2*math.asin(n/H))/4.0))
    
    NameError: name 'sin' is not defined
    
  2. 有零除法

    ---> 26 Direction = math.atan(Fy/Fx)
    
    ZeroDivisionError: float division by zero
    

    n/H正如@MichaelButscher所说,这源于整数除法。

  3. 没有sqrt内置,也可以使用math.sqrt

    ---> 30 Magnitude = sqrt(Fx*Fy + Fy*Fy)
    
    NameError: name 'sqrt' is not defined
    
  4. 如果输入是floats,它们将被截断为ints,这似乎是不必要的。

最终更正的代码:

import math
from decimal import *
from __future__ import division

H = 10.0 # raw_input("Please enter hight:")
H = float(H)
m = 0.2 # raw_input("Please enter crest thickness:")
m = float(m)
n = 2.0 # raw_input("Please enter base thikness:")
n = float(n)

Fx = 0.0
Fy = 0.0
Magnitude = 0.0
Direction = 0.0

p = 1000 #dencity
g = 9.81 #gravity

R = math.sqrt(H*H + n*n)
#Force in x direction
Fx = (-p*g*m*(H*H))/2.0
#Force in y direction
Fy = -p*g*R*(((math.asin(n/H))/2.0)-math.sin((2*math.asin(n/H))/4.0))

#Overall force
Direction = math.atan(Fy/Fx)
Magnitude = math.sqrt(Fx*Fy + Fy*Fy)

print ("The force magnitude is", Magnitude)
print ("The force direction is", Direction)

('The force magnitude is', 1291.77652735702)
('The force direction is', 0.00017336501979739458)
于 2015-05-04T00:15:46.547 回答