亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

"errorMessage": "[<class 'decimal.Inexact'>

"errorMessage": "[<class 'decimal.Inexact'>

喵喵時光機 2023-03-22 16:10:21
代碼如下import jsonfrom decimal import Decimalfrom pprint import pprintimport boto3def update_movie(title, year, rating=None, plot=None, actors=None, dynamodb=None):    if not dynamodb:        dynamodb = boto3.resource('dynamodb')    table = dynamodb.Table('Movies')    response = table.update_item(        Key={            'year': year,            'title': title        },        UpdateExpression="set info.rating=:r, info.plot=:p, info.actors=:a",        ExpressionAttributeValues={            ':r': Decimal(rating),            ':p': plot,            ':a': actors        },        ReturnValues="UPDATED_NEW"    )    return responsedef lambda_handler(event, context):    update_response = update_movie(        "Rush", 2013, 8.3, "Car show",        ["Daniel", "Chris", "Olivia"])    print("Update movie succeeded:")    pprint(update_response, sort_dicts=False)在 dynamodb 中更新密鑰時出現以下錯誤  "errorMessage": "[<class 'decimal.Inexact'>, <class 'decimal.Rounded'>]",  "errorType": "Inexact",如果我更改8.3為8我的代碼工作正常update_response = update_movie(        "Rush", 2013, 8.3, "Car show",        ["Daniel", "Chris", "Olivia"])    print("Update movie succeeded:")``` 
查看完整描述

3 回答

?
慕絲7291255

TA貢獻1859條經驗 獲得超6個贊

問題在于 DynamoDB 的浮點數表示與 Python 的不同:

  1. DynamoDB 以十進制表示浮點數。所以“8.3”可以精確表示——沒有四舍五入或不精確。

  2. Python 使用傳統的 base-2 表示法,因此它不能準確地表示 8.3。8.3 實際上表示為 8.3000000000000007105 并且已知是不精確的(python 不知道你最后想要的數字)。

SDK 知道浮點數 8.3 不準確,并拒絕使用它。

解決方案是按預期使用該類Decimal:它應該使用字符串參數構造,而不是浮點參數。即,使用Decimal("8.3")(注意引號),而不是 Decimal(8.3).

在您上面的代碼中,解決這個問題就像將 8.3 更改為“8.3”(帶引號)一樣簡單。

這是最好的方法。另一種不太好的方法是執行 Decimal(str(8.3))),但要為數字的不精確表示的可能性做好準備。此外,Decimal使用字符串創建 a 允許您創建 Python 根本不支持的數字。例如,Decimal("3.1415926535897932384626433832795028841")將為您提供 38 位十進制數字的精度(DynamoDB 支持的最大值)——這是您在 Python 浮點數中無法做到的。


查看完整回答
反對 回復 2023-03-22
?
慕田峪9158850

TA貢獻1794條經驗 獲得超7個贊

我也遇到了這個問題。我發現該方法的問題Decimal(str(my_float))是它str(my_float)只會保留 16 位有效數字,這對我們來說還不夠。


相反,您可以Decimal在 new 下構造對象decimal.Context,這不會引發[<class 'decimal.Inexact'>, <class 'decimal.Rounded'>]錯誤,因為它沒有設置這些陷阱:


from decimal import Decimal, Context


my_float = 8.3


# 1. Create the context. DynamoDB supports up to 38

# digits of precision.

ctx = Context(prec=38)


# 2. Create the decimal from within the new context, which

# will not raise the Inexact/Rounded error.

my_decimal = ctx.create_decimal_from_float(my_float)


# 3. Save `my_decimal` to DynamoDB without error, and with

# maximum precision preserved.


查看完整回答
反對 回復 2023-03-22
?
瀟瀟雨雨

TA貢獻1833條經驗 獲得超4個贊

一旦嘗試這個:


ExpressionAttributeValues={

            ':r': Decimal(str(rating)),

            ':p': plot,

            ':a': actors

        },


查看完整回答
反對 回復 2023-03-22
  • 3 回答
  • 0 關注
  • 213 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號