【问题标题】:Typeerror: unsupported operand type(s) for /: 'Decimal' and 'float'类型错误:/ 不支持的操作数类型:“十进制”和“浮点”
【发布时间】:2018-10-29 22:23:23
【问题描述】:

这是我的代码:我已经尝试了一整天来解决这个错误,但我仍然有错误:

TypeError: /: 'Decimal' 和 'float' 的操作数类型不受支持。

from math import sqrt, acos, pi

from decimal import Decimal, getcontext

getcontext().prec = 30

class Vector(object):

    CANNOT_NORMALIZE_ZERO_VECTOR_MSG = 'Cannot compute an angle with the zero vector'

    def __init__(self, coordinates):
        try:
            if not coordinates:
                raise ValueError
            self.coordinates = tuple(Decimal(x) for x in coordinates)
            self.dimension = len(self.coordinates)

        except ValueError:
            raise ValueError('The coordinates must be nonempty')

        except TypeError:
            raise TypeError('The coordinates must be an iterable')
    #orthogonal or parallel
    def is_zero(self, tolerance=1e-10):
        return self.magnitude() < tolerance

    def is_orthogonal_to(self, v, tolerance=1e-10):
        return abs(self.dot(v)) < tolerance

    def is_parallel_to(self, v):
        return ( self.is_zero() or 
                v.is_zero() or
                self.angle_with(v) == 0 or
                self.angle_with(v) == pi )

    #dot product &angle
    def dot(self, v):
        return sum([x*y for x,y in zip(self.coordinates,v.coordinates)])
    def angle_with(self,v,in_degrees=False):
        try:
            u1 = self.normalized()
            u2 = v.normalized()
            angle_in_radians = acos(u1.dot(u2))

            if in_degrees:
                degrees_per_radian = 180./pi
                return angle_in_radians * degrees_per_radian
            else:
                return angle_in_radians

        except Exception as e:
            if str(e) == self.CANNOT_NORMALIZE_ZERO_VECTOR_MSG:
                raise Exception('Cannot compute an angle with the zero vector')
            else:
                raise e


    #magnitude& Direction
    def magnitude(self):
        coordinates_squared = [x**2 for x in self.coordinates]
        return sqrt(sum(coordinates_squared))
    def normalized(self):
        try:
            magnitude = self.magnitude()
            return self.times_scalar(Decimal('1.0')/magnitude)
        except ZeroDivisionError:
            raise Exception(self.CANNOT_NORMALIZE_ZERO_VECTOR_MSG)
    #Plus,minus, scalar multiply
    def plus(self, v):
        new_coordinates = [x+y for x,y in zip(self.coordinates,v.coordinates)]
        return Vector(new_coordinates)
    def minus(self, v):
        new_coordinates = [x-y for x,y in zip(self.coordinates,v.coordinates)]
        return Vector(new_coordinates)
    def times_scalar(self, c):
        new_coordinates = [Decimal(c)*x for x in self.coordinates]
        return Vector(new_coordinates)

    def __str__(self):
        return 'Vector: {}'.format(self.coordinates)

    def __eq__(self, v):
        return self.coordinates == v.coordinates

v = Vector(['8','-9'])

w = Vector(['-1','-1'])

print v.dot(w)

print v.angle_with(w)

print v.angle_with(w, in_degrees=True)

【问题讨论】:

    标签: python floating-point


    【解决方案1】:

    一般来说,混合Decimalfloat 数学通常是没有意义的。不知道为什么在这里需要Decimal,但是通过两个小改动,可以运行此代码。我建议考虑摆脱Decimal,除非您确定需要它:

    将幅度更改为:

    # magnitude& Direction
    def magnitude(self):
        coordinates_squared = [x ** 2 for x in self.coordinates]
        return sum(coordinates_squared) ** Decimal('0.5')
    

    还有acos 调用:

    angle_in_radians = Decimal(str(acos(u1.dot(u2))))
    

    【讨论】:

      猜你喜欢
      • 2015-08-04
      • 2017-12-29
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 2014-06-15
      • 2012-11-01
      • 2019-04-08
      • 2019-04-05
      相关资源
      最近更新 更多