diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000000..177b3a3b1a --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,936 @@ +# GitHub Copilot Translation Review Instructions + +**Target**: GitHub Copilot AI Assistant +**Purpose**: Automated translation quality review for Python documentation Traditional Chinese (Taiwan) translations +**Scope**: All Python documentation .po files (library, tutorial, reference, etc.) +**Based on**: Python documentation translation best practices and field experience + +## Critical Review Patterns for AI Analysis + +### Scan Priority Order + +1. **Character Set Validation** (HIGHEST PRIORITY) +2. **Translation Guidelines Compliance** (FROM README.rst) +3. **Markup Preservation** (CRITICAL FOR BUILD) +4. **Cross-file Terminology Consistency** (TECHNICAL ACCURACY) +5. **Formatting Compliance** (READABILITY) +6. **Language Quality** (NATURAL FLOW) + +## 1. Character Set Validation (Critical) + +### Immediate Rejection Patterns + +GitHub Copilot should **IMMEDIATELY FLAG** these simplified Chinese characters: + +```regex +将|应|说|现|来|这|门|时|实|问|样|还|开|关|么|没|总|会|发|进|过|用|作|要|点|别|只|从|而|等|原|及|到|于|很|与|所|又|对|更|并 +``` + +### Correct Traditional Chinese Mappings + +```yaml +# AI Review Pattern: Character Replacement Mapping +simplified_to_traditional: + 将: 將 + 应: 應 + 说: 說 + 现: 現 + 来: 來 + 这: 這 + 门: 門 + 时: 時 + 实: 實 + 问: 問 + 样: 樣 + 还: 還 + 开: 開 + 关: 關 + 发: 發 + 进: 進 + 过: 過 + 总: 總 + 会: 會 + 用: 用 # same + 作: 作 # same + 点: 點 +``` + +### AI Detection Command + +```bash +# Command for Copilot to suggest: +grep -n "将\|应\|说\|现\|来\|这\|门\|时\|实\|问\|样\|还\|开\|关\|么\|没\|总\|会\|发\|进\|过" file.po +``` + +## 2. Translation Guidelines Compliance (From README.rst) + +### Core Translation Rules + +GitHub Copilot should **enforce** these exact rules from README.rst: + +#### Rule 1: Full-width vs Half-width Punctuation + +```yaml +# AI Rule: Chinese text uses full-width punctuation +chinese_punctuation: + required: "「」()、,。:;!?" + forbidden: "\"\"(),;!?:" + +# AI Rule: English text uses half-width punctuation +english_punctuation: + required: "\"\"(),;!?:" + forbidden: "「」()、,。:;!?" +``` + +#### Rule 2: Chinese-English Spacing + +```regex +# MANDATORY spacing patterns from README.rst: +[一-龯]\s+[a-zA-Z] # Chinese + space + English +[a-zA-Z]\s+[一-龯] # English + space + Chinese +使用\s+CPU\s+運算 # Example: "使用 CPU 運算" +使用「CPU」運算 # Alternative: "使用「CPU」運算" +``` + +#### Rule 3: High-frequency Terms (Keep English) + +```yaml +# From README.rst - These MUST remain in English: +preserve_english_terms: + - "int" + - "float" + - "str" + - "bytes" + - "list" + - "tuple" + - "dict" + - "set" + - "iterator" + - "generator" + - "iterable" + - "pickle" + +# AI validation pattern: +correct: "list 物件" ✅ +wrong: "串列物件" ❌ (Should use English "list") +``` + +#### Rule 4: Technical Terms with Brackets + +```regex +# Pattern: First occurrence includes English in brackets +正規表示式\s+\(regular\s+expression\) +Network\s+News\s+Transfer\s+Protocol、Portable\s+Network\s+Graphics(可攜式網路圖形) + +# AI Rule: First mention includes bracketed explanation +首次提及: "正規表示式 (regular expression)" ✅ +後續提及: "正規表示式" ✅ +``` + +#### Rule 5: Bracket Usage Rules + +```yaml +# From README.rst bracket rules: +chinese_content_brackets: "()" # Full-width for Chinese content +english_content_brackets: "()" # Half-width for English only +mixed_content: "前後加空白" # Spacing around half-width brackets + +# Examples AI should approve: +- "list(串列)是 Python 中很常見的資料型別。" ✅ +- "在本情況使用 ``zip(*[iter(x)]*n)`` 是很常見的情況(Python 慣例)。" ✅ +- "在超文件標示語言 (HTML) 中應注意跳脫符號。" ✅ +``` + +#### Rule 6: reStructuredText Formatting Rules + +```yaml +# From README.rst - reStructuredText specific rules: +preserve_markup: ":func:`name`" # Keep markup exactly +chinese_colon_rule: ": ::" # Chinese colon + space + double colon +hyperlink_preservation: true # Keep original link text + +# Examples from README.rst: +original: "Here is a code example::" +chinese: "以下是個程式範例: ::" # Note: Chinese colon + space + :: + +original: "For more information, please see :ref:`detail-instruction`." +chinese: "更多資訊請參考\\ :ref:`detail-instruction`。" # Note: backslash escape +``` + +## 3. Punctuation Pattern Analysis + +### Punctuation Classification Rules + +GitHub Copilot should enforce these **exact patterns**: + +#### Chinese Text Patterns (Full-width Required) + +```regex +# Pattern: Chinese characters followed by punctuation +[一-龯]+[,。:;!?「」()] + +# Examples AI should approve: +模組提供對 Python 程式設計的強大支援。 ✅ +使用「list」資料型別進行操作。 ✅ +這包括三個概念:物件、方法和屬性。 ✅ +``` + +#### English Text Patterns (Half-width Required) + +```regex +# Pattern: English text with half-width punctuation +[a-zA-Z0-9\s]+[,.;!?()"] + +# Examples AI should approve: +See PEP 8 style guide (Section 4). ✅ +The function returns True or False. ✅ +Available in Python 3.8+. ✅ +``` + +#### Violation Patterns (Auto-flag) + +```regex +# AI should FLAG these patterns immediately: +[一-龯]+[,.;!?()"] # Chinese + half-width punctuation +[a-zA-Z]+[,。:;] # English + full-width punctuation + +# Examples AI should reject: +模組提供支援. ❌ (Chinese with half-width period) +使用"decimal"模組 ❌ (English quotes in Chinese text) +Python的功能 ❌ (No space between Chinese and English) +``` + +## 3. Spacing Pattern Enforcement + +### Mandatory Spacing Patterns + +GitHub Copilot should **enforce** these exact regex patterns: + +#### Required Space Patterns + +```regex +# Pattern 1: Chinese + Space + English +[一-龯]\s+[a-zA-Z] +# Example: 使用 decimal 模組 + +# Pattern 2: English + Space + Chinese +[a-zA-Z]\s+[一-龯] +# Example: Python 模組 + +# Pattern 3: Chinese + Space + Numbers +[一-龯]\s+\d +# Example: 設定 28 位精度 + +# Pattern 4: Chinese + Space + Technical Terms +[一-龯]\s+[A-Z][a-zA-Z]* +# Example: 呼叫 CPU 功能 +``` + +#### Violation Patterns (Auto-reject) + +```regex +# AI should immediately flag: +[一-龯][a-zA-Z] # No space between Chinese-English +[a-zA-Z][一-龯] # No space between English-Chinese +[一-龯]\d # No space between Chinese-numbers + +# Examples to reject: +使用decimal模組 ❌ +Python模組 ❌ +設定28位 ❌ +``` + +### Spacing Verification Algorithm + +```python +# Copilot should use this logic: +def check_spacing(text): + violations = [] + + # Check Chinese-English boundaries + if re.search(r'[一-龯][a-zA-Z]', text): + violations.append("Missing space between Chinese and English") + + # Check English-Chinese boundaries + if re.search(r'[a-zA-Z][一-龯]', text): + violations.append("Missing space between English and Chinese") + + # Check Chinese-number boundaries + if re.search(r'[一-龯]\d', text): + violations.append("Missing space between Chinese and numbers") + + return violations +``` + +## 4. reStructuredText Markup Preservation + +### Critical Markup Patterns + +GitHub Copilot must **preserve exactly** these patterns: + +#### Cross-reference Patterns + +```regex +# Pattern: Role references (must remain unchanged) +:func:`[^`]+` # Function references +:class:`[^`]+` # Class references +:meth:`[^`]+` # Method references +:const:`[^`]+` # Constant references +:attr:`[^`]+` # Attribute references +:exc:`[^`]+` # Exception references + +# AI Validation: These should appear IDENTICALLY in Chinese translation +Original: :func:`getcontext` +Chinese: :func:`getcontext` ✅ (exact match required) +``` + +#### Code Block Patterns + +```regex +# Pattern: Code block indicators +^.*:: *$ # Ending with double colon + +# AI Rule: Transform pattern for Chinese +Original: "Here is an example::" +Chinese: "以下是範例: ::" +# ↑ Chinese colon + space + double colon +``` + +#### Inline Code Patterns + +```regex +# Pattern: Inline code (preserve exactly) +``[^`]+`` # Double backtick code + +# Examples AI should preserve: +``Decimal('3.14')`` ✅ (unchanged in translation) +``1.1 + 2.2`` ✅ (unchanged in translation) +``` + +#### Markup Violation Patterns + +```regex +# AI should FLAG these immediately: +:func: `[^`]+` # Space in markup (WRONG) +:class:`[^`]+ # Unclosed markup (WRONG) +[^:]:func:`[^`]+` # Missing leading colon (WRONG) + +# Auto-rejection examples: +:func: `getcontext` ❌ (space after colon) +:class:`Decimal ❌ (missing closing backtick) +``` + +## 5. Cross-file Terminology Consistency + +### Project-wide Consistency Validation + +GitHub Copilot should **validate consistency across ALL .po files**: + +#### Cross-file Consistency Algorithm + +```python +# Copilot should use this logic for multi-file validation: +def validate_cross_file_consistency(po_files_list): + term_translations = {} + + # Scan all .po files for translations of core terms + for po_file in po_files_list: + for english_term in CORE_TERMS: + chinese_translations = extract_translations(po_file, english_term) + + if english_term not in term_translations: + term_translations[english_term] = {} + + for chinese_term in chinese_translations: + if chinese_term in term_translations[english_term]: + term_translations[english_term][chinese_term].append(po_file) + else: + term_translations[english_term][chinese_term] = [po_file] + + # Flag inconsistencies + inconsistencies = [] + for english_term, chinese_variants in term_translations.items(): + if len(chinese_variants) > 1: + inconsistencies.append({ + 'term': english_term, + 'variants': chinese_variants + }) + + return inconsistencies + +# Example inconsistency report: +# { +# 'term': 'context', +# 'variants': { +# '情境': ['library/decimal.po', 'tutorial/classes.po'], +# '上下文': ['library/logging.po'] # INCONSISTENT - should be 情境 +# } +# } +``` + +#### Cross-file Validation Commands + +```bash +# Commands for Copilot to suggest for consistency checking: + +# Extract all translations of "context" across project +find . -name "*.po" -exec grep -l "context" {} \; | xargs grep -A1 "msgid.*context" + +# Check consistency of key terms across files +for term in "context" "precision" "rounding" "signal" "exception"; do + echo "=== Checking term: $term ===" + find . -name "*.po" -exec grep -l "$term" {} \; | xargs grep -A1 "msgid.*$term" +done + +# Generate consistency report +python3 -c " +import glob +import re + +def extract_term_translations(po_files, term): + results = {} + for po_file in po_files: + with open(po_file, 'r', encoding='utf-8') as f: + content = f.read() + # Find msgid/msgstr pairs containing the term + pattern = rf'msgid.*{term}.*\nmsgstr \"([^\"]+)\"' + matches = re.findall(pattern, content, re.IGNORECASE) + if matches: + results[po_file] = matches + return results + +po_files = glob.glob('**/*.po', recursive=True) +terms = ['context', 'precision', 'rounding', 'signal', 'exception'] + +for term in terms: + print(f'\\n=== {term.upper()} ===') + translations = extract_term_translations(po_files, term) + for po_file, chinese_terms in translations.items(): + print(f'{po_file}: {chinese_terms}') +" +``` + +### Mandatory Translation Mappings + +GitHub Copilot should **enforce** these exact mappings across ALL files: + +#### Core Term Dictionary + +```yaml +# CRITICAL: These must be translated consistently +technical_terms: + # Core concepts + "context": "情境" # NEVER "內容" or "上下文" + "precision": "精度" # NEVER "精確度" + "rounding": "捨入" # NEVER "四捨五入" + "signal": "訊號" # NEVER "信號" + "exception": "例外" # NEVER "異常" + "algorithm": "演算法" # NEVER "算法" + "implementation": "實作" # NEVER "實現" + "application": "應用程式" # NEVER "應用" + + # Data types + "integer": "整數" + "string": "字串" + "tuple": "元組" + "instance": "實例" + "object": "物件" + "argument": "引數" # NEVER "參數" + "parameter": "參數" # NEVER "引數" +``` + +#### Preserve-in-English Terms + +```yaml +# HIGH-FREQUENCY: Keep these in English (per README.rst) +preserve_english: + - "decimal" + - "float" + - "int" + - "str" + - "bytes" + - "list" + - "tuple" + - "dict" + - "set" + - "iterator" + - "generator" + - "pickle" + - "NaN" + - "Infinity" + +# Usage pattern AI should enforce: +"decimal 模組" ✅ (English term + Chinese) +"十進位模組" ❌ (Should use English "decimal") +"list 物件" ✅ (English term + Chinese) +"串列物件" ❌ (Should use English "list") +``` + +#### Cross-project Terminology Validation Algorithm + +```python +# Copilot should check consistency across entire project: +def validate_project_terminology(project_root): + term_usage = {} + inconsistencies = [] + + # Scan all .po files in project + po_files = glob.glob(f"{project_root}/**/*.po", recursive=True) + + for po_file in po_files: + # Extract all translations of key terms + for english_term, expected_chinese in CORE_TERMS.items(): + occurrences = find_term_translations(po_file, english_term) + + for chinese_translation in occurrences: + if chinese_translation != expected_chinese: + inconsistencies.append({ + 'file': po_file, + 'english': english_term, + 'found': chinese_translation, + 'expected': expected_chinese + }) + + return inconsistencies + +# Example inconsistency output: +# [ +# { +# 'file': 'library/logging.po', +# 'english': 'context', +# 'found': '上下文', +# 'expected': '情境' +# } +# ] +``` + +## 6. Emphasis and Formatting Patterns + +### Emphasis Markup Rules + +GitHub Copilot should validate **paired emphasis markers**: + +#### Correct Emphasis Patterns + +```regex +# Pattern: Paired asterisks with content +\*[^*]+\* # Single emphasis +\*\*[^*]+\*\* # Strong emphasis + +# Examples AI should approve: +這是 *正常* 有限數 ✅ (properly paired) +接受兩個 *logical operands* ✅ (with trailing space) +``` + +#### Emphasis Violation Patterns + +```regex +# AI should immediately FLAG: +\*[^*]*$ # Unclosed emphasis (line ending) +\*[^*]*\n # Unclosed emphasis (newline) + +# Examples to reject: +接受兩個 *logical operands*( ❌ (missing space before Chinese) +這是 *正常 ❌ (unclosed emphasis) +``` + +### Emphasis Validation Algorithm + +```python +# Copilot validation logic: +def validate_emphasis(line): + # Count asterisks + single_asterisks = line.count('*') - line.count('**') * 2 + + # Single asterisks must be even (paired) + if single_asterisks % 2 != 0: + return "ERROR: Unmatched emphasis asterisks" + + # Check for proper spacing + if re.search(r'\*[^*]+\*[一-龯]', line): + return "ERROR: Missing space after emphasis before Chinese" + + return "OK" +``` + +## 7. Code Comment Translation Patterns + +### Code Block Analysis Rules + +GitHub Copilot should handle code blocks with these **exact patterns**: + +#### Comment Translation Requirements + +```python +# Pattern: Translate comments, preserve code +# Original: +# Set default precision ← TRANSLATE THIS +decimal.getcontext().prec = 28 ← PRESERVE THIS + +# Expected translation: +# 設定預設精度 ← TRANSLATED COMMENT +decimal.getcontext().prec = 28 ← UNCHANGED CODE +``` + +#### Docstring Translation Requirements + +```python +# Pattern: Translate docstrings completely +def moneyfmt(value): + """Convert Decimal to money format. ← TRANSLATE + + Args: ← TRANSLATE + value: Decimal value ← TRANSLATE + """ + +# Expected: +def moneyfmt(value): + """將 Decimal 轉換為金額格式。 ← TRANSLATED + + Args: ← TRANSLATED + value: Decimal 值 ← TRANSLATED + """ +``` + +#### Code Modification Violations + +```python +# AI should REJECT any code changes: +# Original: +getcontext().prec = 7 + +# WRONG - Code modified: +getcontext().精度 = 7 ❌ (Code translated - WRONG) + +# CORRECT - Code preserved: +getcontext().prec = 7 ✅ (Code unchanged - CORRECT) +``` + +## 8. Build Validation Patterns + +### Sphinx Warning Detection + +GitHub Copilot should recognize these **critical warning patterns**: + +#### Critical Build Errors + +```regex +# Patterns AI should detect in build output: +WARNING.*Inline emphasis start-string without end-string +WARNING.*inconsistent term references.*original.*translated +ERROR.*InvalidOperation +WARNING.*document is referenced in multiple toctrees +``` + +#### Build Success Indicators + +```regex +# Patterns indicating successful build: +build succeeded +The HTML pages are in build/html +writing output.*\[100%\] +``` + +#### Auto-fix Suggestions + +```yaml +# Common fixes Copilot should suggest: +warning_fixes: + "Inline emphasis start-string without end-string": + problem: "Unmatched * asterisks in translation" + solution: "Add trailing space after emphasis: '*term* '" + + "inconsistent term references": + problem: "Missing reStructuredText reference" + solution: "Ensure :attr:`Term` appears in translation" + + "Invalid markup": + problem: "Broken reStructuredText syntax" + solution: "Check double backticks and colon syntax" +``` + +## 9. Automated Quality Metrics + +### Scoring Algorithm for Copilot + +```python +def calculate_translation_quality_score(translation): + """ + GitHub Copilot should use this scoring system: + 100 = Perfect translation + 0 = Completely unusable + """ + score = 100 + + # Character set compliance (40 points) + if has_simplified_chinese(translation): + score -= 40 # CRITICAL FAILURE + + # Markup preservation (25 points) + markup_violations = count_markup_violations(translation) + score -= markup_violations * 5 + + # Terminology consistency (20 points) + term_violations = count_terminology_violations(translation) + score -= term_violations * 2 + + # Formatting compliance (10 points) + format_violations = count_format_violations(translation) + score -= format_violations * 1 + + # Language quality (5 points) + if has_grammar_issues(translation): + score -= 5 + + return max(0, score) # Never below 0 + +# Copilot acceptance thresholds: +# 90-100: Excellent - Accept immediately +# 80-89: Good - Accept with minor suggestions +# 70-79: Fair - Accept with major revisions needed +# 0-69: Poor - Reject with detailed feedback +``` + +## 10. Automated Review Commands + +### Commands for Copilot to Suggest + +#### Character Validation + +```bash +# Check for simplified Chinese in any .po file +find . -name "*.po" -exec grep -Hn "将\|应\|说\|现\|来\|这\|门\|时\|实\|问\|样\|还\|开\|关" {} \; + +# Check spacing issues across all translation files +find . -name "*.po" -exec grep -Hn "[一-龯][a-zA-Z]\|[a-zA-Z][一-龯]" {} \; + +# Check punctuation mixing in all .po files +find . -name "*.po" -exec grep -Hn "[一-龯][,.;!?()\"]\|[a-zA-Z][,。:;]" {} \; +``` + +#### Markup Validation + +```bash +# Check broken markup across all .po files +find . -name "*.po" -exec grep -Hn ":func: \|:class: \|:meth: " {} \; + +# Check unmatched emphasis in all translation files +find . -name "*.po" -exec grep -Hn "\*[^*]*$" {} \; + +# Check format validity for specific file or all files +msgfmt --check-format library/file.po # For specific file +find . -name "*.po" -exec msgfmt --check-format {} \; # For all files +``` + +#### Build Testing + +```bash +# Full build test for specific file or entire project +make build library/file.po # For specific file +make build # For entire project + +# Quick syntax check for any documentation file +sphinx-build -b html -D language=zh_TW . build/test file.rst + +# Warning extraction from build output +make build 2>&1 | grep -E "(WARNING|ERROR)" + +# Check untranslated entries in any .po file +msgattrib --untranslated library/file.po | grep ^msgid | sed 1d | wc -l +``` + +## 11. Structured Feedback Templates + +### Feedback Format for Copilot + +#### Approval Message Template + +```markdown +## ✅ TRANSLATION APPROVED + +**Quality Score: [XX]/100** + +### Strengths: +- ✅ Traditional Chinese characters correct +- ✅ Markup preservation perfect +- ✅ Terminology consistent +- ✅ Build passes without warnings + +### Minor Suggestions: +- [Optional improvements] + +**Status: READY FOR MERGE** +``` + +#### Rejection Message Template + +```markdown +## ❌ TRANSLATION REQUIRES REVISION + +**Quality Score: [XX]/100** + +### Critical Issues (Must Fix): +- 🚨 Simplified Chinese characters found: [list] +- 🚨 Broken markup: [details] +- 🚨 Build failures: [error messages] + +### Major Issues (Should Fix): +- ⚠️ Terminology inconsistencies: [list] +- ⚠️ Formatting violations: [details] + +### Suggested Fixes: +```bash +# Command to fix simplified characters in any .po file: +sed -i 's/将/將/g' path/to/file.po + +# Command to check build for any file: +make build path/to/file.po +``` + +**Status: NEEDS REVISION** +``` + +#### Revision Request Template + +```markdown +## 🔄 TRANSLATION NEEDS IMPROVEMENT + +**Quality Score: [XX]/100** + +### Good Aspects: +- ✅ [What works well] + +### Areas for Improvement: +1. **Character Issues**: [specific problems] +2. **Markup Issues**: [specific problems] +3. **Terminology Issues**: [specific problems] + +### Priority Actions: +1. Fix simplified Chinese: `find . -name "*.po" -exec grep -n "将" {} \;` +2. Validate markup: `make build path/to/file.po` +3. Check README.rst compliance: Review punctuation, spacing, bracket usage +4. Check terminology consistency: [review specific terms across project] + +**Status: REVISION REQUESTED** +``` + +## 12. Integration with Development Workflow + +### GitHub Actions Integration + +```yaml +# Example workflow for Copilot to suggest: +name: Translation Quality Check +on: [pull_request] + +jobs: + translation-review: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Check Simplified Chinese + run: | + if find . -name "*.po" -exec grep -q "将\|应\|说\|现\|来\|这" {} \;; then + echo "❌ Simplified Chinese characters found" + exit 1 + fi + + - name: Validate Markup + run: | + make build # Build entire project + + - name: Check Terminology Consistency + run: | + # Check for consistent terminology across all .po files + python3 -c " + import glob + import re + import sys + + # Core terms that must be consistent across project + CORE_TERMS = { + 'context': '情境', + 'precision': '精度', + 'rounding': '捨入', + 'signal': '訊號', + 'exception': '例外', + 'algorithm': '演算法', + 'implementation': '實作', + 'application': '應用程式' + } + + inconsistencies = [] + po_files = glob.glob('**/*.po', recursive=True) + + for po_file in po_files: + with open(po_file, 'r', encoding='utf-8') as f: + content = f.read() + for english_term, expected_chinese in CORE_TERMS.items(): + # Find msgid/msgstr pairs + pattern = rf'msgid.*{english_term}.*\nmsgstr \"([^\"]+)\"' + matches = re.findall(pattern, content, re.IGNORECASE) + for match in matches: + if match and match != expected_chinese: + inconsistencies.append(f'{po_file}: {english_term} -> {match} (expected: {expected_chinese})') + + if inconsistencies: + print('❌ Terminology inconsistencies found:') + for issue in inconsistencies: + print(f' {issue}') + sys.exit(1) + else: + print('✅ All terminology consistent across project') + " +``` + +### Copilot Review Triggers + +```yaml +# When Copilot should automatically review: +auto_review_triggers: + - file_pattern: "**/*.po" + - change_type: "translation" + - size_threshold: "> 10 lines changed" + +review_focus: + - character_validation: "always" + - markup_preservation: "always" + - terminology_consistency: "if > 5 terms changed" + - build_validation: "always" +``` + +## Conclusion for GitHub Copilot + +This guide provides **structured patterns and algorithms** for GitHub Copilot to: + +1. **Automatically detect** common translation issues +2. **Enforce README.rst guidelines** for proper formatting +3. **Validate cross-file consistency** for terminology +4. **Provide actionable feedback** with specific fixes +5. **Score translation quality** objectively +6. **Integrate seamlessly** with development workflows + +### Key Success Metrics + +- **Zero simplified Chinese characters** in approved translations +- **100% README.rst compliance** for formatting and style +- **Cross-file terminology consistency** using established mappings +- **100% markup preservation** for build compatibility +- **Clean builds** with no Sphinx warnings +- **Natural Chinese expression** maintaining technical accuracy + +### Usage Instruction for Copilot + +Apply this guide systematically to **every translation review**, prioritizing: +1. Character validation (Traditional Chinese) +2. README.rst guidelines compliance +3. Cross-file terminology consistency +4. Markup preservation for builds + +These are critical factors for approval. + +**Version**: 1.0 +**Last Updated**: Based on Python documentation translation project +**Maintainer**: Python Documentation Translation Team +**Purpose**: Automated quality assurance for Traditional Chinese translations \ No newline at end of file diff --git a/library/decimal.po b/library/decimal.po index 384c9f1508..1b7c912845 100644 --- a/library/decimal.po +++ b/library/decimal.po @@ -32,6 +32,8 @@ msgid "" "decimal floating-point arithmetic. It offers several advantages over the :" "class:`float` datatype:" msgstr "" +":mod:`decimal` 模組提供對快速正確捨入的十進位浮點運算的支援。相較於 :class:" +"`float` 資料型別,它提供了幾個優勢:" #: ../../library/decimal.rst:37 msgid "" @@ -41,6 +43,9 @@ msgid "" "people learn at school.\" -- excerpt from the decimal arithmetic " "specification." msgstr "" +"Decimal「基於一個以人為設計考量的浮點模型,並且必然有一個至關重要的指導原則 " +"—— 電腦必須提供與人們在學校學習的算術運算方式相同的算術運算。」—— 摘自十進位" +"算術規範。" #: ../../library/decimal.rst:42 msgid "" @@ -49,6 +54,9 @@ msgid "" "point. End users typically would not expect ``1.1 + 2.2`` to display as " "``3.3000000000000003`` as it does with binary floating point." msgstr "" +"Decimal 數字可以被精確表示。相對地,像 ``1.1`` 和 ``2.2`` 這樣的數字在二進位" +"浮點數中沒有精確的表示方式。終端使用者通常不會期望 ``1.1 + 2.2`` 顯示為 " +"``3.3000000000000003``,但這正是二進位浮點數的表現。" #: ../../library/decimal.rst:47 msgid "" @@ -59,6 +67,10 @@ msgid "" "accumulate. For this reason, decimal is preferred in accounting applications " "which have strict equality invariants." msgstr "" +"精確性延續到算術運算中。在十進位浮點數中,``0.1 + 0.1 + 0.1 - 0.3`` 完全" +"等於零。在二進位浮點數中,結果是 ``5.5511151231257827e-017``。雖然接近零," +"但這些差異會妨礙可靠的相等性測試,並且差異可能累積。因此,在具有嚴格相等" +"不變量的會計應用程式中,decimal 是首選。" #: ../../library/decimal.rst:54 msgid "" @@ -69,6 +81,10 @@ msgid "" "multiplicands. For instance, ``1.3 * 1.2`` gives ``1.56`` while ``1.30 * " "1.20`` gives ``1.5600``." msgstr "" +"decimal 模組納入了有效位數的概念,使得 ``1.30 + 1.20`` 等於 ``2.50``。尾隨" +"零被保留以表示有效性。這是金融應用程式的慣例表示法。對於乘法,「課本」方法" +"使用被乘數中的所有數字。例如,``1.3 * 1.2`` 得到 ``1.56``,而 ``1.30 * " +"1.20`` 得到 ``1.5600``。" #: ../../library/decimal.rst:61 msgid "" @@ -76,6 +92,8 @@ msgid "" "alterable precision (defaulting to 28 places) which can be as large as " "needed for a given problem:" msgstr "" +"與基於硬體的二進位浮點數不同,decimal 模組具有使用者可變的精度(預設為 28 位)," +"可以根據給定問題的需要設定得足夠大:" #: ../../library/decimal.rst:73 msgid "" @@ -86,6 +104,10 @@ msgid "" "signal handling. This includes an option to enforce exact arithmetic by " "using exceptions to block any inexact operations." msgstr "" +"二進位和十進位浮點數都是根據已發布的標準實作的。雖然內建的 float 型別只" +"暴露其功能的一小部分,但 decimal 模組暴露了標準的所有必要部分。必要時," +"程式設計師對捨入和訊號處理有完全的控制權。這包括透過使用例外來阻止任何" +"不精確運算以強制執行精確算術的選項。" #: ../../library/decimal.rst:80 msgid "" @@ -94,12 +116,15 @@ msgid "" "rounded floating-point arithmetic.\" -- excerpt from the decimal arithmetic " "specification." msgstr "" +"decimal 模組被設計為支援「無偏見地支援精確的未捨入十進位算術(有時稱為定點" +"算術)和捨入浮點算術。」—— 摘自十進位算術規範。" #: ../../library/decimal.rst:85 msgid "" "The module design is centered around three concepts: the decimal number, " "the context for arithmetic, and signals." msgstr "" +"模組設計圍繞三個概念:decimal 數字、算術情境和訊號。" #: ../../library/decimal.rst:88 msgid "" @@ -109,6 +134,9 @@ msgid "" "``-Infinity``, and ``NaN``. The standard also differentiates ``-0`` from " "``+0``." msgstr "" +"decimal 數字是不可變的。它有符號、係數數字和指數。為了保持有效性,係數數字" +"不會截斷尾隨零。Decimal 也包含特殊值,如 ``Infinity``、``-Infinity`` 和 " +"``NaN``。標準也區分 ``-0`` 和 ``+0``。" #: ../../library/decimal.rst:94 msgid "" @@ -119,6 +147,11 @@ msgid "" "`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`, :const:" "`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`." msgstr "" +"算術情境是一個指定精度、捨入規則、指數限制、指示運算結果的旗標,以及決定" +"訊號是否被視為例外的陷阱啟用器的環境。捨入選項包括 :const:`ROUND_CEILING`、" +":const:`ROUND_DOWN`、:const:`ROUND_FLOOR`、:const:`ROUND_HALF_DOWN`、:const:" +"`ROUND_HALF_EVEN`、:const:`ROUND_HALF_UP`、:const:`ROUND_UP` 和 :const:" +"`ROUND_05UP`。" #: ../../library/decimal.rst:101 msgid "" @@ -130,6 +163,11 @@ msgid "" "`Subnormal`, :const:`Overflow`, :const:`Underflow` and :const:" "`FloatOperation`." msgstr "" +"訊號是在計算過程中產生的例外條件群組。根據應用程式的需求,訊號可能被忽略、" +"視為資訊性質,或被視為例外。decimal 模組中的訊號包括::const:`Clamped`、" +":const:`InvalidOperation`、:const:`DivisionByZero`、:const:`Inexact`、:const:" +"`Rounded`、:const:`Subnormal`、:const:`Overflow`、:const:`Underflow` 和 " +":const:`FloatOperation`。" #: ../../library/decimal.rst:108 msgid "" @@ -138,16 +176,21 @@ msgid "" "one, an exception is raised. Flags are sticky, so the user needs to reset " "them before monitoring a calculation." msgstr "" +"每個訊號都有一個旗標和一個陷阱啟用器。當遇到訊號時,其旗標被設定為一,然後," +"如果陷阱啟用器被設定為一,就會引發例外。旗標是黏性的,因此使用者需要在監控" +"計算之前重設它們。" #: ../../library/decimal.rst:116 msgid "" "IBM's General Decimal Arithmetic Specification, `The General Decimal " "Arithmetic Specification `_." msgstr "" +"IBM 的一般十進位算術規範,`一般十進位算術規範 " +"`_。" #: ../../library/decimal.rst:125 msgid "Quick-start tutorial" -msgstr "" +msgstr "快速入門教學" #: ../../library/decimal.rst:127 msgid "" @@ -155,6 +198,8 @@ msgid "" "current context with :func:`getcontext` and, if necessary, setting new " "values for precision, rounding, or enabled traps::" msgstr "" +"使用 decimal 的通常起始步驟是引入模組、使用 :func:`getcontext` 檢視目前的情境," +"以及若有必要的話,設定精度、捨入方式或啟用陷阱的新值: ::" #: ../../library/decimal.rst:131 msgid "" @@ -166,6 +211,13 @@ msgid "" "\n" ">>> getcontext().prec = 7 # Set a new precision" msgstr "" +">>> from decimal import *\n" +">>> getcontext()\n" +"Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,\n" +" capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,\n" +" InvalidOperation])\n" +"\n" +">>> getcontext().prec = 7 # 設定新的精度" #: ../../library/decimal.rst:139 msgid "" @@ -175,6 +227,9 @@ msgid "" "values such as ``NaN`` which stands for \"Not a number\", positive and " "negative ``Infinity``, and ``-0``::" msgstr "" +"Decimal 實例可以從整數、字串、浮點數或元組建構。從整數或浮點數建構會執行該整數" +"或浮點數值的精確轉換。Decimal 數字包含特殊值,例如代表「非數字」的 ``NaN``、" +"正負 ``Infinity``,以及 ``-0``: ::" #: ../../library/decimal.rst:145 msgid "" @@ -220,6 +275,8 @@ msgid "" "decimals and floats in constructors or ordering comparisons raises an " "exception::" msgstr "" +"如果 :exc:`FloatOperation` 訊號被捕捉,在建構函式或排序比較中意外混用 decimal " +"和 float 會引發例外: ::" #: ../../library/decimal.rst:167 msgid "" @@ -255,6 +312,8 @@ msgid "" "digits input. Context precision and rounding only come into play during " "arithmetic operations." msgstr "" +"新 Decimal 的精度僅由輸入的數字位數決定。情境精度和捨入只會在算術運算期間" +"發揮作用。" #: ../../library/decimal.rst:186 msgid "" @@ -285,6 +344,7 @@ msgid "" "If the internal limits of the C version are exceeded, constructing a decimal " "raises :class:`InvalidOperation`::" msgstr "" +"如果超過 C 版本的內部限制,建構 decimal 會引發 :class:`InvalidOperation`: ::" #: ../../library/decimal.rst:202 msgid "" @@ -303,6 +363,7 @@ msgid "" "Decimals interact well with much of the rest of Python. Here is a small " "decimal floating-point flying circus:" msgstr "" +"Decimal 與 Python 的其他部分互動良好。以下是一個小小的 decimal 浮點數展示:" #: ../../library/decimal.rst:212 msgid "" @@ -360,7 +421,7 @@ msgstr "" #: ../../library/decimal.rst:241 msgid "And some mathematical functions are also available to Decimal:" -msgstr "" +msgstr "而且 Decimal 也提供一些數學函式:" #: ../../library/decimal.rst:253 msgid "" @@ -368,6 +429,8 @@ msgid "" "This method is useful for monetary applications that often round results to " "a fixed number of places:" msgstr "" +":meth:`~Decimal.quantize` 方法將數字捨入到固定的指數。此方法對於經常將結果捨入" +"到固定位數的金融應用程式很有用:" #: ../../library/decimal.rst:262 msgid "" @@ -375,6 +438,8 @@ msgid "" "and allows the settings to be changed. This approach meets the needs of " "most applications." msgstr "" +"如上所示,:func:`getcontext` 函式存取目前的情境並允許變更設定。這種方法滿足" +"大多數應用程式的需求。" #: ../../library/decimal.rst:266 msgid "" @@ -382,6 +447,8 @@ msgid "" "the Context() constructor. To make an alternate active, use the :func:" "`setcontext` function." msgstr "" +"對於更進階的工作,使用 Context() 建構函式建立替代情境可能會很有用。要使替代" +"情境作用,請使用 :func:`setcontext` 函式。" #: ../../library/decimal.rst:270 msgid "" @@ -390,6 +457,8 @@ msgid "" "`ExtendedContext`. The former is especially useful for debugging because " "many of the traps are enabled:" msgstr "" +"根據標準,:mod:`decimal` 模組提供兩個現成可用的標準情境,:const:`BasicContext` " +"和 :const:`ExtendedContext`。前者特別適用於除錯,因為許多陷阱都已啟用:" #: ../../library/decimal.rst:275 msgid "" @@ -442,6 +511,9 @@ msgid "" "cleared, so it is best to clear the flags before each set of monitored " "computations by using the :meth:`~Context.clear_flags` method. ::" msgstr "" +"情境也有訊號旗標用於監控計算過程中遇到的例外條件。旗標會保持設定狀態直到" +"明確清除,因此最好在每組受監控的計算之前使用 :meth:`~Context.clear_flags` " +"方法清除旗標: ::" #: ../../library/decimal.rst:304 msgid "" @@ -467,12 +539,15 @@ msgid "" "(digits beyond the context precision were thrown away) and that the result " "is inexact (some of the discarded digits were non-zero)." msgstr "" +"*flags* 條目顯示對 pi 的有理逼近已被捨入(超出情境精度的數字被丟棄),並且" +"結果是不精確的(一些被丟棄的數字非零)。" #: ../../library/decimal.rst:316 msgid "" "Individual traps are set using the dictionary in the :attr:`~Context.traps` " "attribute of a context:" msgstr "" +"個別陷阱使用情境的 :attr:`~Context.traps` 屬性中的字典設定:" #: ../../library/decimal.rst:319 msgid "" @@ -504,14 +579,17 @@ msgid "" "the bulk of the program manipulates the data no differently than with other " "Python numeric types." msgstr "" +"大多數程式只在程式開始時調整一次目前情境。在許多應用程式中,資料在迴圈內" +"透過單次轉換轉換為 :class:`Decimal`。設定情境並建立 decimal 後,程式的大部分" +"操作資料的方式與其他 Python 數值型別沒有什麼不同。" #: ../../library/decimal.rst:343 msgid "Decimal objects" -msgstr "" +msgstr "Decimal 物件" #: ../../library/decimal.rst:348 msgid "Construct a new :class:`Decimal` object based from *value*." -msgstr "" +msgstr "基於 *value* 建構一個新的 :class:`Decimal` 物件。" #: ../../library/decimal.rst:350 msgid "" @@ -521,6 +599,9 @@ msgid "" "after leading and trailing whitespace characters, as well as underscores " "throughout, are removed::" msgstr "" +"*value* 可以是整數、字串、元組、:class:`float` 或其他 :class:`Decimal` 物件。" +"如果沒有提供 *value*,則回傳 ``Decimal('0')``。如果 *value* 是字串,在移除" +"前後空白字元以及整個字串中的底線後,它應該符合十進位數字字串語法: ::" #: ../../library/decimal.rst:355 msgid "" @@ -536,6 +617,17 @@ msgid "" "numeric-value ::= decimal-part [exponent-part] | infinity\n" "numeric-string ::= [sign] numeric-value | [sign] nan" msgstr "" +"sign ::= '+' | '-'\n" +"digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | " +"'9'\n" +"indicator ::= 'e' | 'E'\n" +"digits ::= digit [digit]...\n" +"decimal-part ::= digits '.' [digits] | ['.'] digits\n" +"exponent-part ::= indicator [sign] digits\n" +"infinity ::= 'Infinity' | 'Inf'\n" +"nan ::= 'NaN' [digits] | 'sNaN' [digits]\n" +"numeric-value ::= decimal-part [exponent-part] | infinity\n" +"numeric-string ::= [sign] numeric-value | [sign] nan" #: ../../library/decimal.rst:366 msgid "" @@ -546,6 +638,10 @@ msgid "" "example, ``inf``, ``Inf``, ``INFINITY``, and ``iNfINity`` are all acceptable " "spellings for positive infinity." msgstr "" +"在上面出現 ``digit`` 的地方也允許其他 Unicode 十進位數字。這些包括來自各種其他" +"字母表的十進位數字(例如阿拉伯-印度數字和天城數字)以及全形數字 ``'\\uff10'`` " +"到 ``'\\uff19'``。大小寫不重要,所以例如 ``inf``、``Inf``、``INFINITY`` 和 " +"``iNfINity`` 都是正無窮大的可接受拼寫。" #: ../../library/decimal.rst:373 msgid "" @@ -554,6 +650,9 @@ msgid "" "an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))`` returns " "``Decimal('1.414')``." msgstr "" +"如果 *value* 是 :class:`tuple`,它應該有三個元件:一個符號(``0`` 代表正數或 " +"``1`` 代表負數)、一個數字的 :class:`tuple`,以及一個整數指數。例如," +"``Decimal((0, (1, 4, 1, 4), -3))`` 回傳 ``Decimal('1.414')``。" #: ../../library/decimal.rst:378 msgid "" @@ -563,6 +662,9 @@ msgid "" "``Decimal(float('1.1'))`` converts to " "``Decimal('1.100000000000000088817841970012523233890533447265625')``." msgstr "" +"如果 *value* 是 :class:`float`,二進位浮點數值會被無損轉換為其精確的十進位" +"等價值。這種轉換通常需要 53 位或更多位數的精度。例如,``Decimal(float('1.1'))`` " +"轉換為 ``Decimal('1.100000000000000088817841970012523233890533447265625')``。" #: ../../library/decimal.rst:384 msgid "" @@ -571,6 +673,8 @@ msgid "" "``Decimal('3.00000')`` records all five zeros even if the context precision " "is only three." msgstr "" +"*context* 精度不會影響儲存多少位數。這完全由 *value* 中的位數決定。例如,即使" +"情境精度只有三位,``Decimal('3.00000')`` 也會記錄所有五個零。" #: ../../library/decimal.rst:389 msgid "" @@ -579,28 +683,35 @@ msgid "" "exception is raised; otherwise, the constructor returns a new Decimal with " "the value of ``NaN``." msgstr "" +"*context* 引數的目的是決定當 *value* 是格式不正確的字串時該怎麼辦。如果情境" +"捕捉 :const:`InvalidOperation`,就會引發例外;否則,建構函式會回傳一個值為 " +"``NaN`` 的新 Decimal。" #: ../../library/decimal.rst:394 msgid "Once constructed, :class:`Decimal` objects are immutable." -msgstr "" +msgstr "一旦建構,:class:`Decimal` 物件就是不可變的。" #: ../../library/decimal.rst:396 msgid "" "The argument to the constructor is now permitted to be a :class:`float` " "instance." msgstr "" +"建構函式的引數現在允許是 :class:`float` 實例。" #: ../../library/decimal.rst:400 msgid "" ":class:`float` arguments raise an exception if the :exc:`FloatOperation` " "trap is set. By default the trap is off." msgstr "" +"如果設定了 :exc:`FloatOperation` 陷阱,:class:`float` 引數會引發例外。預設" +"情況下陷阱是關閉的。" #: ../../library/decimal.rst:404 msgid "" "Underscores are allowed for grouping, as with integral and floating-point " "literals in code." msgstr "" +"允許使用底線進行分組,就像程式碼中的整數和浮點數字面值一樣。" #: ../../library/decimal.rst:408 msgid "" @@ -611,6 +722,10 @@ msgid "" "compared, sorted, and coerced to another type (such as :class:`float` or :" "class:`int`)." msgstr "" +"Decimal 浮點數物件與其他內建數值型別(如 :class:`float` 和 :class:`int`)共享" +"許多屬性。所有常用的數學運算和特殊方法都適用。同樣地,decimal 物件可以被複製、" +"pickle 序列化、列印、用作字典鍵、用作集合元素、比較、排序,以及強制轉換為其他" +"型別(如 :class:`float` 或 :class:`int`)。" #: ../../library/decimal.rst:415 msgid "" @@ -619,6 +734,8 @@ msgid "" "applied to Decimal objects, the sign of the result is the sign of the " "*dividend* rather than the sign of the divisor::" msgstr "" +"Decimal 物件的算術運算與整數和浮點數的算術運算之間有一些小差異。當餘數運算子 " +"``%`` 應用於 Decimal 物件時,結果的符號是 *被除數* 的符號,而不是除數的符號: ::" #: ../../library/decimal.rst:420 msgid "" @@ -638,6 +755,8 @@ msgid "" "integer part of the true quotient (truncating towards zero) rather than its " "floor, so as to preserve the usual identity ``x == (x // y) * y + x % y``::" msgstr "" +"整數除法運算子 ``//`` 的行為類似,回傳真商的整數部分(向零截斷)而不是其底數," +"以保持通常的恆等式 ``x == (x // y) * y + x % y``: ::" #: ../../library/decimal.rst:429 msgid "" @@ -656,6 +775,8 @@ msgid "" "The ``%`` and ``//`` operators implement the ``remainder`` and ``divide-" "integer`` operations (respectively) as described in the specification." msgstr "" +"``%`` 和 ``//`` 運算子分別實作規格中描述的 ``remainder`` 和 ``divide-integer`` " +"運算。" #: ../../library/decimal.rst:438 msgid "" @@ -667,18 +788,25 @@ msgid "" "This avoids confusing results when doing equality comparisons between " "numbers of different types." msgstr "" +"Decimal 物件通常不能在算術運算中與浮點數或 :class:`fractions.Fraction` 實例" +"結合:例如,嘗試將 :class:`Decimal` 與 :class:`float` 相加會引發 :exc:" +"`TypeError`。但是,可以使用 Python 的比較運算子來比較 :class:`Decimal` 實例 " +"``x`` 與另一個數字 ``y``。這避免了在不同型別的數字之間進行相等比較時產生" +"令人困惑的結果。" #: ../../library/decimal.rst:446 msgid "" "Mixed-type comparisons between :class:`Decimal` instances and other numeric " "types are now fully supported." msgstr "" +":class:`Decimal` 實例與其他數值型別之間的混合型別比較現在完全支援。" #: ../../library/decimal.rst:450 msgid "" "In addition to the standard numeric properties, decimal floating-point " "objects also have a number of specialized methods:" msgstr "" +"除了標準數值屬性外,decimal 浮點數物件也有許多專門的方法:" #: ../../library/decimal.rst:456 msgid "" @@ -687,6 +815,8 @@ msgid "" "returns seven. Used for determining the position of the most significant " "digit with respect to the decimal point." msgstr "" +"在移出係數的最右邊數字直到只剩下前導數字後,回傳調整後的指數:" +"``Decimal('321e+5').adjusted()`` 回傳七。用於確定最高有效數字相對於小數點的位置。" #: ../../library/decimal.rst:463 msgid "" @@ -694,6 +824,8 @@ msgid "" "`Decimal` instance as a fraction, in lowest terms and with a positive " "denominator::" msgstr "" +"回傳一對表示給定 :class:`Decimal` 實例作為分數的整數 ``(n, d)``,以最簡形式" +"且分母為正: ::" #: ../../library/decimal.rst:467 msgid "" @@ -708,12 +840,15 @@ msgid "" "The conversion is exact. Raise OverflowError on infinities and ValueError " "on NaNs." msgstr "" +"轉換是精確的。對無窮大引發 OverflowError,對 NaN 引發 ValueError。" #: ../../library/decimal.rst:477 msgid "" "Return a :term:`named tuple` representation of the number: " "``DecimalTuple(sign, digits, exponent)``." msgstr "" +"回傳數字的 :term:`named tuple` 表示形式:" +"``DecimalTuple(sign, digits, exponent)``。" #: ../../library/decimal.rst:483 msgid "" @@ -721,12 +856,16 @@ msgid "" "a :class:`Decimal` instance is always canonical, so this operation returns " "its argument unchanged." msgstr "" +"回傳引數的標準編碼。目前,:class:`Decimal` 實例的編碼總是標準的,因此此運算" +"回傳其引數不變。" #: ../../library/decimal.rst:489 msgid "" "Compare the values of two Decimal instances. :meth:`compare` returns a " "Decimal instance, and if either operand is a NaN then the result is a NaN::" msgstr "" +"比較兩個 Decimal 實例的值。:meth:`compare` 回傳一個 Decimal 實例,如果任一" +"運算元是 NaN,則結果是 NaN: ::" #: ../../library/decimal.rst:493 msgid "" @@ -746,6 +885,9 @@ msgid "" "NaNs signal. That is, if neither operand is a signaling NaN then any quiet " "NaN operand is treated as though it were a signaling NaN." msgstr "" +"此運算與 :meth:`compare` 方法相同,除了所有 NaN 都會發出訊號。也就是說,如果" +"兩個運算元都不是發出訊號的 NaN,那麼任何安靜的 NaN 運算元都會被視為發出訊號的 " +"NaN。" #: ../../library/decimal.rst:506 msgid "" @@ -755,6 +897,9 @@ msgid "" "instances with the same numeric value but different representations compare " "unequal in this ordering:" msgstr "" +"使用抽象表示而不是數值來比較兩個運算元。類似於 :meth:`compare` 方法,但結果" +"對 :class:`Decimal` 實例給出全序。在此排序中,具有相同數值但不同表示的兩個 " +":class:`Decimal` 實例比較為不相等:" #: ../../library/decimal.rst:515 msgid "" @@ -765,6 +910,10 @@ msgid "" "in the total order than the second operand. See the specification for " "details of the total order." msgstr "" +"安靜和發出訊號的 NaN 也包含在全序中。如果兩個運算元具有相同的表示,此函式的" +"結果是 ``Decimal('0')``;如果第一個運算元在全序中低於第二個,則為 " +"``Decimal('-1')``;如果第一個運算元在全序中高於第二個運算元,則為 " +"``Decimal('1')``。有關全序的詳細資訊,請參閱規範。" #: ../../library/decimal.rst:522 ../../library/decimal.rst:533 #: ../../library/decimal.rst:561 ../../library/decimal.rst:848 @@ -773,6 +922,8 @@ msgid "" "and no rounding is performed. As an exception, the C version may raise " "InvalidOperation if the second operand cannot be converted exactly." msgstr "" +"此運算不受情境影響且是安靜的:不會變更旗標也不會執行捨入。例外情況下,如果" +"第二個運算元無法精確轉換,C 版本可能會引發 InvalidOperation。" #: ../../library/decimal.rst:528 msgid "" @@ -781,30 +932,37 @@ msgid "" "``x.compare_total_mag(y)`` is equivalent to ``x.copy_abs().compare_total(y." "copy_abs())``." msgstr "" +"如 :meth:`compare_total` 般使用抽象表示而不是值來比較兩個運算元,但忽略每個" +"運算元的符號。``x.compare_total_mag(y)`` 等於 ``x.copy_abs().compare_total" +"(y.copy_abs())``。" #: ../../library/decimal.rst:539 msgid "" "Just returns self, this method is only to comply with the Decimal " "Specification." msgstr "" +"只是回傳 self,此方法僅為符合 Decimal 規範。" #: ../../library/decimal.rst:544 msgid "" "Return the absolute value of the argument. This operation is unaffected by " "the context and is quiet: no flags are changed and no rounding is performed." msgstr "" +"回傳引數的絕對值。此運算不受情境影響且是安靜的:不會變更旗標也不會執行捨入。" #: ../../library/decimal.rst:550 msgid "" "Return the negation of the argument. This operation is unaffected by the " "context and is quiet: no flags are changed and no rounding is performed." msgstr "" +"回傳引數的否定。此運算不受情境影響且是安靜的:不會變更旗標也不會執行捨入。" #: ../../library/decimal.rst:555 msgid "" "Return a copy of the first operand with the sign set to be the same as the " "sign of the second operand. For example:" msgstr "" +"回傳第一個運算元的副本,其符號被設定為與第二個運算元的符號相同。例如:" #: ../../library/decimal.rst:567 msgid "" @@ -812,12 +970,15 @@ msgid "" "number. The result is correctly rounded using the :const:`ROUND_HALF_EVEN` " "rounding mode." msgstr "" +"回傳給定數字的(自然)指數函式 ``e**x`` 的值。使用 :const:`ROUND_HALF_EVEN` " +"捨入模式正確地捨入結果。" #: ../../library/decimal.rst:578 msgid "" "Alternative constructor that only accepts instances of :class:`float` or :" "class:`int`." msgstr "" +"僅接受 :class:`float` 或 :class:`int` 實例的替代建構函式。" #: ../../library/decimal.rst:581 msgid "" @@ -827,12 +988,17 @@ msgid "" "``0x1.999999999999ap-4``. That equivalent value in decimal is " "``0.1000000000000000055511151231257827021181583404541015625``." msgstr "" +"注意 ``Decimal.from_float(0.1)`` 與 ``Decimal('0.1')`` 不同。由於 0.1 在" +"二進位浮點數中無法精確表示,該值被儲存為最接近的可表示值 " +"``0x1.999999999999ap-4``。該值在十進位中的等價值是 " +"``0.1000000000000000055511151231257827021181583404541015625``。" #: ../../library/decimal.rst:587 msgid "" "From Python 3.2 onwards, a :class:`Decimal` instance can also be constructed " "directly from a :class:`float`." msgstr "" +"從 Python 3.2 開始,:class:`Decimal` 實例也可以直接從 :class:`float` 建構。" #: ../../library/decimal.rst:590 msgid "" @@ -859,6 +1025,7 @@ msgid "" "Fused multiply-add. Return self*other+third with no rounding of the " "intermediate product self*other." msgstr "" +"融合乘加。回傳 self*other+third,對中間產品 self*other 不進行捨入。" #: ../../library/decimal.rst:613 msgid "" @@ -866,72 +1033,88 @@ msgid "" "otherwise. Currently, a :class:`Decimal` instance is always canonical, so " "this operation always returns :const:`True`." msgstr "" +"如果引數是標準形式則回傳 :const:`True`,否則回傳 :const:`False`。目前," +":class:`Decimal` 實例總是標準形式,因此此運算總是回傳 :const:`True`。" #: ../../library/decimal.rst:619 msgid "" "Return :const:`True` if the argument is a finite number, and :const:`False` " "if the argument is an infinity or a NaN." msgstr "" +"如果引數是有限數則回傳 :const:`True`,如果引數是無窮大或 NaN 則回傳 " +":const:`False`。" #: ../../library/decimal.rst:624 msgid "" "Return :const:`True` if the argument is either positive or negative infinity " "and :const:`False` otherwise." msgstr "" +"如果引數是正無窮大或負無窮大則回傳 :const:`True`,否則回傳 :const:`False`。" #: ../../library/decimal.rst:629 msgid "" "Return :const:`True` if the argument is a (quiet or signaling) NaN and :" "const:`False` otherwise." msgstr "" +"如果引數是(安靜或發出訊號的)NaN 則回傳 :const:`True`,否則回傳 :const:`False`。" #: ../../library/decimal.rst:634 msgid "" "Return :const:`True` if the argument is a *normal* finite number. Return :" "const:`False` if the argument is zero, subnormal, infinite or a NaN." msgstr "" +"如果引數是 *正常* 有限數則回傳 :const:`True`。如果引數是零、次正規、無窮大" +"或 NaN 則回傳 :const:`False`。" #: ../../library/decimal.rst:639 msgid "" "Return :const:`True` if the argument is a quiet NaN, and :const:`False` " "otherwise." msgstr "" +"如果引數是安靜 NaN 則回傳 :const:`True`,否則回傳 :const:`False`。" #: ../../library/decimal.rst:644 msgid "" "Return :const:`True` if the argument has a negative sign and :const:`False` " "otherwise. Note that zeros and NaNs can both carry signs." msgstr "" +"如果引數具有負號則回傳 :const:`True`,否則回傳 :const:`False`。注意零和 NaN " +"都可以帶有符號。" #: ../../library/decimal.rst:649 msgid "" "Return :const:`True` if the argument is a signaling NaN and :const:`False` " "otherwise." msgstr "" +"如果引數是發出訊號的 NaN 則回傳 :const:`True`,否則回傳 :const:`False`。" #: ../../library/decimal.rst:654 msgid "" "Return :const:`True` if the argument is subnormal, and :const:`False` " "otherwise." msgstr "" +"如果引數是次正規則回傳 :const:`True`,否則回傳 :const:`False`。" #: ../../library/decimal.rst:659 msgid "" "Return :const:`True` if the argument is a (positive or negative) zero and :" "const:`False` otherwise." msgstr "" +"如果引數是(正或負)零則回傳 :const:`True`,否則回傳 :const:`False`。" #: ../../library/decimal.rst:664 msgid "" "Return the natural (base e) logarithm of the operand. The result is " "correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode." msgstr "" +"回傳運算元的自然(以 e 為底)對數。使用 :const:`ROUND_HALF_EVEN` 捨入模式正確地捨入結果。" #: ../../library/decimal.rst:669 msgid "" "Return the base ten logarithm of the operand. The result is correctly " "rounded using the :const:`ROUND_HALF_EVEN` rounding mode." msgstr "" +"回傳運算元的十進位對數。使用 :const:`ROUND_HALF_EVEN` 捨入模式正確地捨入結果。" #: ../../library/decimal.rst:674 msgid "" @@ -940,6 +1123,9 @@ msgid "" "Infinity')`` is returned and the :const:`DivisionByZero` flag is raised. If " "the operand is an infinity then ``Decimal('Infinity')`` is returned." msgstr "" +"對於非零數字,回傳其運算元的調整指數作為 :class:`Decimal` 實例。如果運算元是零," +"則回傳 ``Decimal('-Infinity')`` 並引發 :const:`DivisionByZero` 旗標。如果運算元" +"是無窮大,則回傳 ``Decimal('Infinity')``。" #: ../../library/decimal.rst:682 msgid "" @@ -947,12 +1133,15 @@ msgid "" "operands* (see :ref:`logical_operands_label`). The result is the digit-wise " "``and`` of the two operands." msgstr "" +":meth:`logical_and` 是一個邏輯運算,接受兩個 *logical operands* " +"(參見 :ref:`logical_operands_label`)。結果是兩個運算元的逐位 ``and``。" #: ../../library/decimal.rst:688 msgid "" ":meth:`logical_invert` is a logical operation. The result is the digit-wise " "inversion of the operand." msgstr "" +":meth:`logical_invert` 是一個邏輯運算。結果是運算元的逐位反轉。" #: ../../library/decimal.rst:693 msgid "" @@ -960,6 +1149,8 @@ msgid "" "(see :ref:`logical_operands_label`). The result is the digit-wise ``or`` of " "the two operands." msgstr "" +":meth:`logical_or` 是一個邏輯運算,接受兩個 *logical operands* " +"(參見 :ref:`logical_operands_label`)。結果是兩個運算元的逐位 ``or``。" #: ../../library/decimal.rst:699 msgid "" @@ -967,6 +1158,8 @@ msgid "" "operands* (see :ref:`logical_operands_label`). The result is the digit-wise " "exclusive or of the two operands." msgstr "" +":meth:`logical_xor` 是一個邏輯運算,接受兩個 *logical operands* " +"(參見 :ref:`logical_operands_label`)。結果是兩個運算元的逐位互斥或。" #: ../../library/decimal.rst:705 msgid "" @@ -974,12 +1167,15 @@ msgid "" "before returning and that ``NaN`` values are either signaled or ignored " "(depending on the context and whether they are signaling or quiet)." msgstr "" +"類似於 ``max(self, other)``,但在回傳前會套用情境捨入規則,且 ``NaN`` 值會" +"被發出訊號或忽略(取決於情境以及它們是發出訊號或安靜的)。" #: ../../library/decimal.rst:712 msgid "" "Similar to the :meth:`.max` method, but the comparison is done using the " "absolute values of the operands." msgstr "" +"類似於 :meth:`.max` 方法,但比較是使用運算元的絕對值進行的。" #: ../../library/decimal.rst:717 msgid "" @@ -987,12 +1183,15 @@ msgid "" "before returning and that ``NaN`` values are either signaled or ignored " "(depending on the context and whether they are signaling or quiet)." msgstr "" +"類似於 ``min(self, other)``,但在回傳前會套用情境捨入規則,且 ``NaN`` 值會" +"被發出訊號或忽略(取決於情境以及它們是發出訊號或安靜的)。" #: ../../library/decimal.rst:724 msgid "" "Similar to the :meth:`.min` method, but the comparison is done using the " "absolute values of the operands." msgstr "" +"類似於 :meth:`.min` 方法,但比較是使用運算元的絕對值進行的。" #: ../../library/decimal.rst:729 msgid "" @@ -1000,6 +1199,8 @@ msgid "" "current thread's context if no context is given) that is smaller than the " "given operand." msgstr "" +"回傳在給定情境中(或如果沒有提供情境則在目前執行緒的情境中)可表示的最大數字," +"且該數字小於給定的運算元。" #: ../../library/decimal.rst:735 msgid "" @@ -1007,6 +1208,8 @@ msgid "" "current thread's context if no context is given) that is larger than the " "given operand." msgstr "" +"回傳在給定情境中(或如果沒有提供情境則在目前執行緒的情境中)可表示的最小數字," +"且該數字大於給定的運算元。" #: ../../library/decimal.rst:741 msgid "" @@ -1015,12 +1218,16 @@ msgid "" "numerically equal, return a copy of the first operand with the sign set to " "be the same as the sign of the second operand." msgstr "" +"如果兩個運算元不相等,回傳在第二個運算元方向上最接近第一個運算元的數字。" +"如果兩個運算元在數值上相等,回傳第一個運算元的副本,其符號設定為與第二個" +"運算元的符號相同。" #: ../../library/decimal.rst:748 msgid "" "Used for producing canonical values of an equivalence class within either " "the current context or the specified context." msgstr "" +"用於在目前情境或指定情境中產生等價類別的標準值。" #: ../../library/decimal.rst:751 msgid "" @@ -1031,78 +1238,97 @@ msgid "" "exponent is incremented by 1. Otherwise (the coefficient is zero) the " "exponent is set to 0. In all cases the sign is unchanged." msgstr "" +"這與一元加法運算的語意相同,但如果最終結果是有限的,則會被簡化為最簡形式," +"移除所有尾隨零並保留符號。也就是說,當係數非零且是十的倍數時,係數除以十," +"指數增加 1。否則(係數為零)指數設定為 0。在所有情況下符號都不變。" #: ../../library/decimal.rst:758 msgid "" "For example, ``Decimal('32.100')`` and ``Decimal('0.321000e+2')`` both " "normalize to the equivalent value ``Decimal('32.1')``." msgstr "" +"例如,``Decimal('32.100')`` 和 ``Decimal('0.321000e+2')`` 都正規化為等價值 " +"``Decimal('32.1')``。" #: ../../library/decimal.rst:761 msgid "Note that rounding is applied *before* reducing to simplest form." msgstr "" +"注意捨入是在簡化為最簡形式 *之前* 套用的。" #: ../../library/decimal.rst:763 msgid "" "In the latest versions of the specification, this operation is also known as " "``reduce``." msgstr "" +"在規格的最新版本中,此運算也被稱為 ``reduce``。" #: ../../library/decimal.rst:768 msgid "" "Return a string describing the *class* of the operand. The returned value " "is one of the following ten strings." msgstr "" +"回傳描述運算元 *類別* 的字串。回傳值是下列十個字串之一。" #: ../../library/decimal.rst:771 msgid "``\"-Infinity\"``, indicating that the operand is negative infinity." msgstr "" +"``\"-Infinity\"``,表示運算元是負無窮大。" #: ../../library/decimal.rst:772 msgid "" "``\"-Normal\"``, indicating that the operand is a negative normal number." msgstr "" +"``\"-Normal\"``,表示運算元是負正規數。" #: ../../library/decimal.rst:773 msgid "" "``\"-Subnormal\"``, indicating that the operand is negative and subnormal." msgstr "" +"``\"-Subnormal\"``,表示運算元是負數且為次正規。" #: ../../library/decimal.rst:774 msgid "``\"-Zero\"``, indicating that the operand is a negative zero." msgstr "" +"``\"-Zero\"``,表示運算元是負零。" #: ../../library/decimal.rst:775 msgid "``\"+Zero\"``, indicating that the operand is a positive zero." msgstr "" +"``\"+Zero\"``,表示運算元是正零。" #: ../../library/decimal.rst:776 msgid "" "``\"+Subnormal\"``, indicating that the operand is positive and subnormal." msgstr "" +"``\"+Subnormal\"``,表示運算元是正數且為次正規。" #: ../../library/decimal.rst:777 msgid "" "``\"+Normal\"``, indicating that the operand is a positive normal number." msgstr "" +"``\"+Normal\"``,表示運算元是正正規數。" #: ../../library/decimal.rst:778 msgid "``\"+Infinity\"``, indicating that the operand is positive infinity." msgstr "" +"``\"+Infinity\"``,表示運算元是正無窮大。" #: ../../library/decimal.rst:779 msgid "``\"NaN\"``, indicating that the operand is a quiet NaN (Not a Number)." msgstr "" +"``\"NaN\"``,表示運算元是安靜 NaN(非數字)。" #: ../../library/decimal.rst:780 msgid "``\"sNaN\"``, indicating that the operand is a signaling NaN." msgstr "" +"``\"sNaN\"``,表示運算元是發出訊號的 NaN。" #: ../../library/decimal.rst:784 msgid "" "Return a value equal to the first operand after rounding and having the " "exponent of the second operand." msgstr "" +"回傳一個值,該值等於第一個運算元在捨入後並具有第二個運算元的指數。" #: ../../library/decimal.rst:790 msgid "" @@ -1111,12 +1337,15 @@ msgid "" "is signaled. This guarantees that, unless there is an error condition, the " "quantized exponent is always equal to that of the right-hand operand." msgstr "" +"與其他運算不同,如果 quantize 運算後係數的長度大於精度,則會發出 :const:" +"`InvalidOperation` 訊號。這保證了除非有錯誤條件,否則量化指數總是等於右運算元的指數。" #: ../../library/decimal.rst:796 msgid "" "Also unlike other operations, quantize never signals Underflow, even if the " "result is subnormal and inexact." msgstr "" +"同樣與其他運算不同,quantize 永遠不會發出 Underflow 訊號,即使結果是次正規且不精確的。" #: ../../library/decimal.rst:799 msgid "" @@ -1126,18 +1355,24 @@ msgid "" "if neither argument is given the rounding mode of the current thread's " "context is used." msgstr "" +"如果第二個運算元的指數大於第一個,則可能需要捨入。在這種情況下,捨入模式由 " +"``rounding`` 引數決定(如果有提供),否則由給定的 ``context`` 引數決定;如果" +"兩個引數都沒有提供,則使用目前執行緒情境的捨入模式。" #: ../../library/decimal.rst:805 msgid "" "An error is returned whenever the resulting exponent is greater than :attr:" "`~Context.Emax` or less than :meth:`~Context.Etiny`." msgstr "" +"當結果指數大於 :attr:`~Context.Emax` 或小於 :meth:`~Context.Etiny` 時會回傳錯誤。" #: ../../library/decimal.rst:810 msgid "" "Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal` class " "does all its arithmetic. Included for compatibility with the specification." msgstr "" +"回傳 ``Decimal(10)``,這是 :class:`Decimal` 類別執行所有算術運算的基數(底數)。" +"包含此項是為了與規格相容。" #: ../../library/decimal.rst:816 msgid "" @@ -1147,10 +1382,14 @@ msgid "" "* other`` where ``n`` is the integer nearest to the exact value of ``self / " "other``, and if two integers are equally near then the even one is chosen." msgstr "" +"回傳 *self* 除以 *other* 的餘數。這與 ``self % other`` 不同之處在於餘數的符號" +"被選擇以最小化其絕對值。更精確地說,回傳值是 ``self - n * other``,其中 ``n`` " +"是最接近 ``self / other`` 精確值的整數,如果兩個整數同樣接近,則選擇偶數。" #: ../../library/decimal.rst:823 msgid "If the result is zero then its sign will be the sign of *self*." msgstr "" +"如果結果是零,則其符號將是 *self* 的符號。" #: ../../library/decimal.rst:834 msgid "" @@ -1163,12 +1402,17 @@ msgid "" "length precision if necessary. The sign and exponent of the first operand " "are unchanged." msgstr "" +"回傳將第一個運算元的數字旋轉第二個運算元指定數量的結果。第二個運算元必須是" +"在 -precision 到 precision 範圍內的整數。第二個運算元的絕對值給出要旋轉的位數。" +"如果第二個運算元是正數,則向左旋轉;否則向右旋轉。第一個運算元的係數如有必要會" +"在左側填補零以達到精度長度。第一個運算元的符號和指數不變。" #: ../../library/decimal.rst:845 msgid "" "Test whether self and other have the same exponent or whether both are " "``NaN``." msgstr "" +"測試 self 和 other 是否具有相同的指數,或兩者是否都是 ``NaN``。" #: ../../library/decimal.rst:854 msgid "" @@ -1176,6 +1420,8 @@ msgid "" "return the first operand multiplied by ``10**other``. The second operand " "must be an integer." msgstr "" +"回傳第一個運算元,其指數由第二個運算元調整。等價地,回傳第一個運算元乘以 " +"``10**other``。第二個運算元必須是整數。" #: ../../library/decimal.rst:860 msgid "" @@ -1187,15 +1433,21 @@ msgid "" "right. Digits shifted into the coefficient are zeros. The sign and " "exponent of the first operand are unchanged." msgstr "" +"回傳將第一個運算元的數字移位第二個運算元指定數量的結果。第二個運算元必須是" +"在 -precision 到 precision 範圍內的整數。第二個運算元的絕對值給出要移位的位數。" +"如果第二個運算元是正數,則向左移位;否則向右移位。移入係數的數字是零。" +"第一個運算元的符號和指數不變。" #: ../../library/decimal.rst:870 msgid "Return the square root of the argument to full precision." msgstr "" +"回傳引數的完整精度平方根。" #: ../../library/decimal.rst:875 ../../library/decimal.rst:1524 msgid "" "Convert to a string, using engineering notation if an exponent is needed." msgstr "" +"轉換為字串,如果需要指數則使用工程記號。" #: ../../library/decimal.rst:877 ../../library/decimal.rst:1526 msgid "" @@ -1203,17 +1455,21 @@ msgid "" "leave up to 3 digits to the left of the decimal place and may require the " "addition of either one or two trailing zeros." msgstr "" +"工程記號的指數是 3 的倍數。這可能在小數點左側留下最多 3 位數字,並可能需要" +"添加一個或兩個尾隨零。" #: ../../library/decimal.rst:881 msgid "" "For example, this converts ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``." msgstr "" +"例如,這將 ``Decimal('123E+1')`` 轉換為 ``Decimal('1.23E+3')``。" #: ../../library/decimal.rst:885 msgid "" "Identical to the :meth:`to_integral_value` method. The ``to_integral`` name " "has been kept for compatibility with older versions." msgstr "" +"與 :meth:`to_integral_value` 方法相同。保留 ``to_integral`` 名稱是為了與舊版本相容。" #: ../../library/decimal.rst:890 msgid "" @@ -1222,6 +1478,9 @@ msgid "" "``rounding`` parameter if given, else by the given ``context``. If neither " "parameter is given then the rounding mode of the current context is used." msgstr "" +"捨入到最近的整數,如果發生捨入則適當地發出 :const:`Inexact` 或 :const:`Rounded` " +"訊號。捨入模式由 ``rounding`` 參數決定(如果有提供),否則由給定的 ``context`` 決定。" +"如果兩個參數都沒有提供,則使用目前情境的捨入模式。" #: ../../library/decimal.rst:898 msgid "" @@ -1229,10 +1488,13 @@ msgid "" "`Rounded`. If given, applies *rounding*; otherwise, uses the rounding " "method in either the supplied *context* or the current context." msgstr "" +"捨入到最近的整數,不發出 :const:`Inexact` 或 :const:`Rounded` 訊號。如果有提供," +"套用 *rounding*;否則,使用提供的 *context* 或目前情境中的捨入方法。" #: ../../library/decimal.rst:902 msgid "Decimal numbers can be rounded using the :func:`.round` function:" msgstr "" +"Decimal 數字可以使用 :func:`.round` 函式進行捨入: ::" #: ../../library/decimal.rst:907 msgid "" @@ -1241,6 +1503,9 @@ msgid "" "class:`Decimal` context. Raises :exc:`OverflowError` if *number* is an " "infinity or :exc:`ValueError` if it is a (quiet or signaling) NaN." msgstr "" +"如果沒有提供 *ndigits* 或為 ``None``,回傳最接近 *number* 的 :class:`int`," +"平局時捨入到偶數,並忽略 :class:`Decimal` 情境的捨入模式。如果 *number* 是" +"無窮大則引發 :exc:`OverflowError`,如果是(安靜或發出訊號的)NaN 則引發 :exc:`ValueError`。" #: ../../library/decimal.rst:913 msgid "" @@ -1253,26 +1518,36 @@ msgid "" "length of the coefficient after the quantize operation would be greater than " "the current context's precision. In other words, for the non-corner cases:" msgstr "" +"如果 *ndigits* 是 :class:`int`,會遵守情境的捨入模式,並回傳代表 *number* " +"捨入到 ``Decimal('1E-ndigits')`` 最近倍數的 :class:`Decimal`;在這種情況下," +"``round(number, ndigits)`` 等價於 ``self.quantize(Decimal('1E-ndigits'))``。" +"如果 *number* 是安靜 NaN 則回傳 ``Decimal('NaN')``。如果 *number* 是無窮大、" +"發出訊號的 NaN,或 quantize 運算後係數的長度大於目前情境的精度,則引發 :class:" +"`InvalidOperation`。換句話說,對於非邊界情況:" #: ../../library/decimal.rst:923 msgid "" "if *ndigits* is positive, return *number* rounded to *ndigits* decimal " "places;" msgstr "" +"如果 *ndigits* 是正數,回傳 *number* 捨入到 *ndigits* 小數位數;" #: ../../library/decimal.rst:925 msgid "if *ndigits* is zero, return *number* rounded to the nearest integer;" msgstr "" +"如果 *ndigits* 是零,回傳 *number* 捨入到最近的整數;" #: ../../library/decimal.rst:926 msgid "" "if *ndigits* is negative, return *number* rounded to the nearest multiple of " "``10**abs(ndigits)``." msgstr "" +"如果 *ndigits* 是負數,回傳 *number* 捨入到 ``10**abs(ndigits)`` 的最近倍數。" #: ../../library/decimal.rst:929 msgid "For example::" msgstr "" +"例如: ::" #: ../../library/decimal.rst:931 msgid "" @@ -1289,10 +1564,23 @@ msgid "" ">>> round(Decimal('3.75'), -1)\n" "Decimal('0E+1')" msgstr "" +">>> from decimal import Decimal, getcontext, ROUND_DOWN\n" +">>> getcontext().rounding = ROUND_DOWN\n" +">>> round(Decimal('3.75')) # 忽略情境捨入\n" +"4\n" +">>> round(Decimal('3.5')) # 平局捨入到偶數\n" +"4\n" +">>> round(Decimal('3.75'), 0) # 使用情境捨入\n" +"Decimal('3')\n" +">>> round(Decimal('3.75'), 1)\n" +"Decimal('3.7')\n" +">>> round(Decimal('3.75'), -1)\n" +"Decimal('0E+1')" #: ../../library/decimal.rst:948 msgid "Logical operands" msgstr "" +"邏輯運算元" #: ../../library/decimal.rst:950 msgid "" @@ -1302,10 +1590,14 @@ msgid "" "`Decimal` instance whose exponent and sign are both zero, and whose digits " "are all either ``0`` or ``1``." msgstr "" +":meth:`~Decimal.logical_and`、:meth:`~Decimal.logical_invert`、:meth:" +"`~Decimal.logical_or` 和 :meth:`~Decimal.logical_xor` 方法期望它們的引數是 " +"*logical operands*。*logical operand* 是指數和符號都為零,且數字全部為 ``0`` " +"或 ``1`` 的 :class:`Decimal` 實例。" #: ../../library/decimal.rst:962 msgid "Context objects" -msgstr "" +msgstr "Context 物件" #: ../../library/decimal.rst:964 msgid "" @@ -1313,26 +1605,31 @@ msgid "" "set rules for rounding, determine which signals are treated as exceptions, " "and limit the range for exponents." msgstr "" +"Context 是算術運算的環境。它們控制精度、設定捨入規則、決定哪些訊號被視為例外," +"並限制指數的範圍。" #: ../../library/decimal.rst:968 msgid "" "Each thread has its own current context which is accessed or changed using " "the :func:`getcontext` and :func:`setcontext` functions:" msgstr "" +"每個執行緒都有自己的目前情境,可以使用 :func:`getcontext` 和 :func:" +"`setcontext` 函式來存取或變更:" #: ../../library/decimal.rst:974 msgid "Return the current context for the active thread." -msgstr "" +msgstr "回傳作用中執行緒的目前情境。" #: ../../library/decimal.rst:979 msgid "Set the current context for the active thread to *c*." -msgstr "" +msgstr "將作用中執行緒的目前情境設定為 *c*。" #: ../../library/decimal.rst:981 msgid "" "You can also use the :keyword:`with` statement and the :func:`localcontext` " "function to temporarily change the active context." msgstr "" +"你也可以使用 :keyword:`with` 陳述句和 :func:`localcontext` 函式來暫時變更作用中的情境。" #: ../../library/decimal.rst:986 msgid "" @@ -1342,6 +1639,9 @@ msgid "" "specified, a copy of the current context is used. The *kwargs* argument is " "used to set the attributes of the new context." msgstr "" +"回傳一個情境管理器,在進入 with 陳述句時會將作用中執行緒的目前情境設定為 *ctx* " +"的副本,並在退出 with 陳述句時恢復先前的情境。如果沒有指定情境,則使用目前情境的" +"副本。*kwargs* 引數用於設定新情境的屬性。" #: ../../library/decimal.rst:992 msgid "" @@ -1349,6 +1649,7 @@ msgid "" "places, performs a calculation, and then automatically restores the previous " "context::" msgstr "" +"例如,以下程式碼將目前的 decimal 精度設定為 42 位,執行計算,然後自動恢復先前的情境: ::" #: ../../library/decimal.rst:995 msgid "" @@ -1359,10 +1660,17 @@ msgid "" " s = calculate_something()\n" "s = +s # Round the final result back to the default precision" msgstr "" +"from decimal import localcontext\n" +"\n" +"with localcontext() as ctx:\n" +" ctx.prec = 42 # 執行高精度計算\n" +" s = calculate_something()\n" +"s = +s # 將最終結果捨入回預設精度" #: ../../library/decimal.rst:1002 msgid "Using keyword arguments, the code would be the following::" msgstr "" +"使用關鍵字引數,程式碼如下: ::" #: ../../library/decimal.rst:1004 msgid "" @@ -1384,18 +1692,23 @@ msgid "" "`Context` doesn't support. Raises either :exc:`TypeError` or :exc:" "`ValueError` if *kwargs* supplies an invalid value for an attribute." msgstr "" +"如果 *kwargs* 提供了 :class:`Context` 不支援的屬性,則引發 :exc:`TypeError`。" +"如果 *kwargs* 為屬性提供了無效值,則引發 :exc:`TypeError` 或 :exc:`ValueError`。" #: ../../library/decimal.rst:1014 msgid "" ":meth:`localcontext` now supports setting context attributes through the use " "of keyword arguments." msgstr "" +":meth:`localcontext` 現在支援透過關鍵字引數來設定 context 屬性。" #: ../../library/decimal.rst:1017 msgid "" "New contexts can also be created using the :class:`Context` constructor " "described below. In addition, the module provides three pre-made contexts:" msgstr "" +"新的 context 也可以使用下面描述的 :class:`Context` 建構子來建立。此外," +"該模組提供了三個預製的 context:" #: ../../library/decimal.rst:1023 msgid "" @@ -1405,11 +1718,15 @@ msgid "" "exceptions) except :const:`Inexact`, :const:`Rounded`, and :const:" "`Subnormal`." msgstr "" +"這是由通用十進位算術規格定義的標準 context。精度設定為九。將位設定" +"為 :const:`ROUND_HALF_UP`。所有標誌都被清除。所有的 trap 都被啟用(視為" +"例外),除了 :const:`Inexact`、:const:`Rounded` 和 :const:`Subnormal`。" #: ../../library/decimal.rst:1029 msgid "" "Because many of the traps are enabled, this context is useful for debugging." msgstr "" +"因為很多 trap 都被啟用,這個 context 對於除錯很有用。" #: ../../library/decimal.rst:1034 msgid "" @@ -1418,6 +1735,9 @@ msgid "" "`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that " "exceptions are not raised during computations)." msgstr "" +"這是由通用十進位算術規格定義的標準 context。精度設定為九。將位設定" +"為 :const:`ROUND_HALF_EVEN`。所有標誌都被清除。沒有 trap 被啟用(因此" +"在運算過程中不會引發例外)。" #: ../../library/decimal.rst:1039 msgid "" @@ -1426,6 +1746,9 @@ msgid "" "exceptions. This allows an application to complete a run in the presence of " "conditions that would otherwise halt the program." msgstr "" +"因為 trap 被停用,這個 context 對於傾向於拿到 ``NaN`` 或 ``Infinity`` " +"結果值而不是引發例外的應用程式很有用。這讓應用程式在存在原本會" +"中止程式的條件時也能完成執行。" #: ../../library/decimal.rst:1047 msgid "" @@ -1434,6 +1757,9 @@ msgid "" "changing the default for new contexts created by the :class:`Context` " "constructor." msgstr "" +"這個 context 被 :class:`Context` 建構子用作新 context 的原型。改變一個" +"字段(例如精度)的效果是改變 :class:`Context` 建構子建立的新 context " +"的預設值。" #: ../../library/decimal.rst:1051 msgid "" @@ -1442,12 +1768,17 @@ msgid "" "defaults. Changing the fields after threads have started is not recommended " "as it would require thread synchronization to prevent race conditions." msgstr "" +"這個 context 在多執行緒環境中最有用。在執行緒啟動之前改變其中一個字段的" +"效果是設定系統級預設值。不建議在執行緒啟動後改變字段,因為這會" +"需要執行緒同步來防止競爵條件。" #: ../../library/decimal.rst:1056 msgid "" "In single threaded environments, it is preferable to not use this context at " "all. Instead, simply create contexts explicitly as described below." msgstr "" +"在單執行緒環境中,最好完全不使用這個 context。取而代之,只需按下面" +"描述的方式明確建立 context。" #: ../../library/decimal.rst:1059 msgid "" @@ -1455,12 +1786,17 @@ msgid "" "rounding`\\ =\\ :const:`ROUND_HALF_EVEN`, and enabled traps for :class:" "`Overflow`, :class:`InvalidOperation`, and :class:`DivisionByZero`." msgstr "" +"預設值為 :attr:`Context.prec`\\ =\\ ``28``、:attr:`Context.rounding`\\ =\\ " +":const:`ROUND_HALF_EVEN`,並啟用 :class:`Overflow`、:class:`InvalidOperation` 和 " +":class:`DivisionByZero` 的 trap。" #: ../../library/decimal.rst:1064 msgid "" "In addition to the three supplied contexts, new contexts can be created with " "the :class:`Context` constructor." msgstr "" +"除了這三個提供的 context 之外,還可以使用 :class:`Context` 建構子建立" +"新的 context。" #: ../../library/decimal.rst:1070 msgid "" @@ -1468,22 +1804,28 @@ msgid "" "default values are copied from the :const:`DefaultContext`. If the *flags* " "field is not specified or is :const:`None`, all flags are cleared." msgstr "" +"建立一個新的 context。如果字段未指定或為 :const:`None`,則從 :const:" +"`DefaultContext` 複製預設值。如果 *flags* 字段未指定或為 :const:`None`," +"則清除所有標誌。" #: ../../library/decimal.rst:1076 msgid "" "An integer in the range [``1``, :const:`MAX_PREC`] that sets the precision " "for arithmetic operations in the context." msgstr "" +"在 [``1``, :const:`MAX_PREC`] 範圍內的整數,用於設定 context 中算術運算的精度。" #: ../../library/decimal.rst:1081 msgid "One of the constants listed in the section `Rounding Modes`_." msgstr "" +"`Rounding Modes`_ 段落中列出的常數之一。" #: ../../library/decimal.rst:1086 msgid "" "Lists of any signals to be set. Generally, new contexts should only set " "traps and leave the flags clear." msgstr "" +"要設定的任何信號列表。一般來說,新 context 應該只設定 trap 並保持標誌清除。" #: ../../library/decimal.rst:1092 msgid "" @@ -1491,6 +1833,8 @@ msgid "" "in the range [:const:`MIN_EMIN`, ``0``], *Emax* in the range [``0``, :const:" "`MAX_EMAX`]." msgstr "" +"指定指數允許的外部限制的整數。*Emin* 必須在 [:const:`MIN_EMIN`、``0``] " +"範圍內,*Emax* 在 [``0``、:const:`MAX_EMAX`] 範圍內。" #: ../../library/decimal.rst:1098 msgid "" @@ -1498,6 +1842,8 @@ msgid "" "with a capital ``E``; otherwise, a lowercase ``e`` is used: " "``Decimal('6.02e+23')``." msgstr "" +"``0`` 或 ``1``(預設)。如果設定為 ``1``,指數用大寫 ``E`` 列印;否則," +"使用小寫 ``e``:``Decimal('6.02e+23')``。" #: ../../library/decimal.rst:1104 msgid "" @@ -1511,6 +1857,12 @@ msgid "" "exponent constraints; this preserves the value of the number but loses " "information about significant trailing zeros. For example::" msgstr "" +"``0``(預設)或 ``1``。如果設定為 ``1``,在此 context 中可表示的 :class:" +"`Decimal` 實例的指數 ``e`` 嚴格限制在 ``Emin - prec + 1 <= e <= Emax - " +"prec + 1`` 範圍內。如果 *clamp* 為 ``0``,則適用較弱的條件::class:`Decimal` " +"實例的調整指數最多為 :attr:`~Context.Emax`。當 *clamp* 為 ``1`` 時,如果可能" +"的話,大的正規數字會減少其指數並在其係數上添加相應數量的零,以符合指數約束;" +"這保留了數字的值,但會失去有關有效尾隨零的資訊。例如: ::" #: ../../library/decimal.rst:1115 msgid "" @@ -1525,6 +1877,7 @@ msgid "" "A *clamp* value of ``1`` allows compatibility with the fixed-width decimal " "interchange formats specified in IEEE 754." msgstr "" +"*clamp* 值為 ``1`` 可以與 IEEE 754 中指定的固定寬度十進位交換格式相容。" #: ../../library/decimal.rst:1121 msgid "" @@ -1538,22 +1891,32 @@ msgid "" "exp(context=C)``. Each :class:`Context` method accepts a Python integer (an " "instance of :class:`int`) anywhere that a Decimal instance is accepted." msgstr "" +":class:`Context` 類別定義了幾個通用方法,以及大量在給定 context 中直接進行算術" +"運算的方法。此外,對於上面描述的每個 :class:`Decimal` 方法(除了 :meth:`~Decimal." +"adjusted` 和 :meth:`~Decimal.as_tuple` 方法之外),都有相對應的 :class:`Context` " +"方法。例如,對於 :class:`Context` 實例 ``C`` 和 :class:`Decimal` 實例 ``x``," +"``C.exp(x)`` 等價於 ``x.exp(context=C)``。每個 :class:`Context` 方法在接受 " +"Decimal 實例的任何地方都接受 Python 整數(:class:`int` 的實例)。" #: ../../library/decimal.rst:1134 msgid "Resets all of the flags to ``0``." msgstr "" +"將所有標誌重設為 ``0``。" #: ../../library/decimal.rst:1138 msgid "Resets all of the traps to ``0``." msgstr "" +"將所有 trap 重設為 ``0``。" #: ../../library/decimal.rst:1144 msgid "Return a duplicate of the context." msgstr "" +"返回 context 的一個副本。" #: ../../library/decimal.rst:1148 msgid "Return a copy of the Decimal instance num." msgstr "" +"返回 Decimal 實例 num 的副本。" #: ../../library/decimal.rst:1152 msgid "" @@ -1561,6 +1924,8 @@ msgid "" "Unlike the :class:`Decimal` constructor, the context precision, rounding " "method, flags, and traps are applied to the conversion." msgstr "" +"從 *num* 建立一個新的 Decimal 實例,但使用 *self* 作為 context。與 :class:" +"`Decimal` 建構子不同,context 精度、四捨五入方法、標誌和 trap 會套用於轉換。" #: ../../library/decimal.rst:1156 msgid "" @@ -1570,6 +1935,9 @@ msgid "" "the following example, using unrounded inputs means that adding zero to a " "sum can change the result:" msgstr "" +"這很有用,因為常數通常會提供比應用程式需要的更高精度。另一個好處是四捨五入" +"立即消除超出當前精度的數字的意外影響。在以下範例中,使用未四捨五入的輸入" +"意味著在總和中加零可能會改變結果:" #: ../../library/decimal.rst:1162 msgid "" @@ -1591,6 +1959,8 @@ msgid "" "the argument is a string, no leading or trailing whitespace or underscores " "are permitted." msgstr "" +"此方法實作了 IBM 規格的 to-number 操作。如果引數是字串,則不允許前導或尾隨的" +"空白字元或底線。" #: ../../library/decimal.rst:1176 msgid "" @@ -1599,6 +1969,9 @@ msgid "" "context precision, rounding method, flags, and traps are applied to the " "conversion." msgstr "" +"從浮點數 *f* 建立一個新的 Decimal 實例,但使用 *self* 作為 context 進行四捨五入。" +"與 :meth:`Decimal.from_float` 類別方法不同,context 精度、四捨五入方法、標誌和 " +"trap 會套用於轉換。" #: ../../library/decimal.rst:1181 msgid "" @@ -1626,10 +1999,13 @@ msgid "" "value for subnormal results. When underflow occurs, the exponent is set to :" "const:`Etiny`." msgstr "" +"返回等於 ``Emin - prec + 1`` 的值,這是次正規結果的最小指數值。當發生下溢時," +"指數設定為 :const:`Etiny`。" #: ../../library/decimal.rst:1202 msgid "Returns a value equal to ``Emax - prec + 1``." msgstr "" +"返回等於 ``Emax - prec + 1`` 的值。" #: ../../library/decimal.rst:1204 msgid "" @@ -1640,177 +2016,223 @@ msgid "" "similar to those for the :class:`Decimal` class and are only briefly " "recounted here." msgstr "" +"處理 decimal 的通常方法是建立 :class:`Decimal` 實例,然後在活動執行緒的" +"當前 context 中進行算術運算。另一種方法是使用 context 方法在特定" +"context 中進行計算。這些方法與 :class:`Decimal` 類別的方法相似,在此僅" +"簡要重述。" #: ../../library/decimal.rst:1214 msgid "Returns the absolute value of *x*." msgstr "" +"返回 *x* 的絕對值。" #: ../../library/decimal.rst:1219 msgid "Return the sum of *x* and *y*." msgstr "" +"返回 *x* 和 *y* 的和。" #: ../../library/decimal.rst:1224 msgid "Returns the same Decimal object *x*." msgstr "" +"返回相同的 Decimal 物件 *x*。" #: ../../library/decimal.rst:1229 msgid "Compares *x* and *y* numerically." msgstr "" +"數值比較 *x* 和 *y*。" #: ../../library/decimal.rst:1234 msgid "Compares the values of the two operands numerically." msgstr "" +"數值比較兩個運算元的值。" #: ../../library/decimal.rst:1239 msgid "Compares two operands using their abstract representation." msgstr "" +"使用兩個運算元的抽象表示法進行比較。" #: ../../library/decimal.rst:1244 msgid "" "Compares two operands using their abstract representation, ignoring sign." msgstr "" +"使用兩個運算元的抽象表示法進行比較,忽略符號。" #: ../../library/decimal.rst:1249 msgid "Returns a copy of *x* with the sign set to 0." msgstr "" +"返回 *x* 的副本,將符號設定為 0。" #: ../../library/decimal.rst:1254 msgid "Returns a copy of *x* with the sign inverted." msgstr "" +"返回 *x* 的副本,將符號反轉。" #: ../../library/decimal.rst:1259 msgid "Copies the sign from *y* to *x*." msgstr "" +"將 *y* 的符號複製到 *x*。" #: ../../library/decimal.rst:1264 msgid "Return *x* divided by *y*." msgstr "" +"返回 *x* 除以 *y*。" #: ../../library/decimal.rst:1269 msgid "Return *x* divided by *y*, truncated to an integer." msgstr "" +"返回 *x* 除以 *y*,截斷為整數。" #: ../../library/decimal.rst:1274 msgid "Divides two numbers and returns the integer part of the result." msgstr "" +"將兩個數相除並返回結果的整數部分。" #: ../../library/decimal.rst:1279 msgid "Returns ``e ** x``." msgstr "" +"返回 ``e ** x``。" #: ../../library/decimal.rst:1284 msgid "Returns *x* multiplied by *y*, plus *z*." msgstr "" +"返回 *x* 乘以 *y* 再加上 *z*。" #: ../../library/decimal.rst:1289 msgid "Returns ``True`` if *x* is canonical; otherwise returns ``False``." msgstr "" +"如果 *x* 是標準形式則返回 ``True``;否則返回 ``False``。" #: ../../library/decimal.rst:1294 msgid "Returns ``True`` if *x* is finite; otherwise returns ``False``." msgstr "" +"如果 *x* 是有限的則返回 ``True``;否則返回 ``False``。" #: ../../library/decimal.rst:1299 msgid "Returns ``True`` if *x* is infinite; otherwise returns ``False``." msgstr "" +"如果 *x* 是無窮大則返回 ``True``;否則返回 ``False``。" #: ../../library/decimal.rst:1304 msgid "Returns ``True`` if *x* is a qNaN or sNaN; otherwise returns ``False``." msgstr "" +"如果 *x* 是 qNaN 或 sNaN 則返回 ``True``;否則返回 ``False``。" #: ../../library/decimal.rst:1309 msgid "" "Returns ``True`` if *x* is a normal number; otherwise returns ``False``." msgstr "" +"如果 *x* 是正規數則返回 ``True``;否則返回 ``False``。" #: ../../library/decimal.rst:1314 msgid "Returns ``True`` if *x* is a quiet NaN; otherwise returns ``False``." msgstr "" +"如果 *x* 是安靜 NaN 則返回 ``True``;否則返回 ``False``。" #: ../../library/decimal.rst:1319 msgid "Returns ``True`` if *x* is negative; otherwise returns ``False``." msgstr "" +"如果 *x* 是負數則返回 ``True``;否則返回 ``False``。" #: ../../library/decimal.rst:1324 msgid "" "Returns ``True`` if *x* is a signaling NaN; otherwise returns ``False``." msgstr "" +"如果 *x* 是發出訊號的 NaN 則返回 ``True``;否則返回 ``False``。" #: ../../library/decimal.rst:1329 msgid "Returns ``True`` if *x* is subnormal; otherwise returns ``False``." msgstr "" +"如果 *x* 是次正規則返回 ``True``;否則返回 ``False``。" #: ../../library/decimal.rst:1334 msgid "Returns ``True`` if *x* is a zero; otherwise returns ``False``." msgstr "" +"如果 *x* 是零則返回 ``True``;否則返回 ``False``。" #: ../../library/decimal.rst:1339 msgid "Returns the natural (base e) logarithm of *x*." msgstr "" +"返回 *x* 的自然(以 e 為底)對數。" #: ../../library/decimal.rst:1344 msgid "Returns the base 10 logarithm of *x*." msgstr "" +"返回 *x* 的十進位對數。" #: ../../library/decimal.rst:1349 msgid "Returns the exponent of the magnitude of the operand's MSD." msgstr "" +"返回運算元的 MSD 量級的指數。" #: ../../library/decimal.rst:1354 msgid "Applies the logical operation *and* between each operand's digits." msgstr "" +"在每個運算元的數字之間套用邏輯運算 *and*。" #: ../../library/decimal.rst:1359 msgid "Invert all the digits in *x*." msgstr "" +"反轉 *x* 中的所有數字。" #: ../../library/decimal.rst:1364 msgid "Applies the logical operation *or* between each operand's digits." msgstr "" +"在每個運算元的數字之間套用邏輯運算 *or*。" #: ../../library/decimal.rst:1369 msgid "Applies the logical operation *xor* between each operand's digits." msgstr "" +"在每個運算元的數字之間套用邏輯運算 *xor*。" #: ../../library/decimal.rst:1374 msgid "Compares two values numerically and returns the maximum." msgstr "" +"數值比較兩個值並返回最大值。" #: ../../library/decimal.rst:1379 ../../library/decimal.rst:1389 msgid "Compares the values numerically with their sign ignored." msgstr "" +"數值比較值,忽略其符號。" #: ../../library/decimal.rst:1384 msgid "Compares two values numerically and returns the minimum." msgstr "" +"數值比較兩個值並返回最小值。" #: ../../library/decimal.rst:1394 msgid "Minus corresponds to the unary prefix minus operator in Python." msgstr "" +"Minus 對應於 Python 中的一元前綴減號運算子。" #: ../../library/decimal.rst:1399 msgid "Return the product of *x* and *y*." msgstr "" +"返回 *x* 和 *y* 的乘積。" #: ../../library/decimal.rst:1404 msgid "Returns the largest representable number smaller than *x*." msgstr "" +"返回小於 *x* 的最大可表示數字。" #: ../../library/decimal.rst:1409 msgid "Returns the smallest representable number larger than *x*." msgstr "" +"返回大於 *x* 的最小可表示數字。" #: ../../library/decimal.rst:1414 msgid "Returns the number closest to *x*, in direction towards *y*." msgstr "" +"返回最接近 *x* 的數字,方向指向 *y*。" #: ../../library/decimal.rst:1419 msgid "Reduces *x* to its simplest form." msgstr "" +"將 *x* 簡化為最簡形式。" #: ../../library/decimal.rst:1424 msgid "Returns an indication of the class of *x*." msgstr "" +"返回 *x* 類別的指示。" #: ../../library/decimal.rst:1429 msgid "" @@ -1818,10 +2240,13 @@ msgid "" "operation applies the context precision and rounding, so it is *not* an " "identity operation." msgstr "" +"Plus 對應於 Python 中的一元前綴加號運算子。此運算會套用 context 精度和" +"將位,因此它 *不是* 一個恆等運算。" #: ../../library/decimal.rst:1436 msgid "Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given." msgstr "" +"返回 ``x`` 的 ``y`` 次方,如果有提供則總是 ``modulo`` 的簡化結果。" #: ../../library/decimal.rst:1438 msgid "" @@ -1831,12 +2256,18 @@ msgid "" "rounding mode of the context is used. Results are always correctly rounded " "in the Python version." msgstr "" +"使用兩個引數計算 ``x**y``。如果 ``x`` 是負數,則 ``y`` 必須是整數。" +"除非 ``y`` 是整數且結果是有限的且可以在「精度」位數中精確表示," +"否則結果將是不精確的。使用 context 的將位模式。在 Python 版本中," +"結果總是正確將位的。" #: ../../library/decimal.rst:1444 msgid "" "``Decimal(0) ** Decimal(0)`` results in ``InvalidOperation``, and if " "``InvalidOperation`` is not trapped, then results in ``Decimal('NaN')``." msgstr "" +"``Decimal(0) ** Decimal(0)`` 會導致 ``InvalidOperation``,如果 ``InvalidOperation`` " +"沒有被捕獲,則會產生 ``Decimal('NaN')``。" #: ../../library/decimal.rst:1447 msgid "" @@ -1844,28 +2275,36 @@ msgid "" "`exp` and :meth:`ln` functions. The result is well-defined but only \"almost " "always correctly rounded\"." msgstr "" +"C 模組以正確將位的 :meth:`exp` 和 :meth:`ln` 函式來計算 :meth:`power`。" +"結果是定義良好的,但只是「幾乎總是正確將位」。" #: ../../library/decimal.rst:1452 msgid "" "With three arguments, compute ``(x**y) % modulo``. For the three argument " "form, the following restrictions on the arguments hold:" msgstr "" +"使用三個引數計算 ``(x**y) % modulo``。對於三個引數的形式,引數有" +"以下限制:" #: ../../library/decimal.rst:1455 msgid "all three arguments must be integral" msgstr "" +"所有三個引數必須是整數" #: ../../library/decimal.rst:1456 msgid "``y`` must be nonnegative" msgstr "" +"``y`` 必須是非負數" #: ../../library/decimal.rst:1457 msgid "at least one of ``x`` or ``y`` must be nonzero" msgstr "" +"``x`` 或 ``y`` 中至少一個必須是非零" #: ../../library/decimal.rst:1458 msgid "``modulo`` must be nonzero and have at most 'precision' digits" msgstr "" +"``modulo`` 必須是非零且最多有「精度」位數" #: ../../library/decimal.rst:1460 msgid "" @@ -1875,62 +2314,78 @@ msgid "" "zero, regardless of the exponents of ``x``, ``y`` and ``modulo``. The " "result is always exact." msgstr "" +"精度,但計算更加高效。結果的指數是零,無論 ``x``、``y`` 和 " +"``modulo`` 的指數如何。結果總是精確的。" #: ../../library/decimal.rst:1470 msgid "Returns a value equal to *x* (rounded), having the exponent of *y*." msgstr "" +"返回等於 *x*(將位後)的值,具有 *y* 的指數。" #: ../../library/decimal.rst:1475 msgid "Just returns 10, as this is Decimal, :)" msgstr "" +"只返回 10,因為這是 Decimal :)" #: ../../library/decimal.rst:1480 msgid "Returns the remainder from integer division." msgstr "" +"返回整數除法的餘數。" #: ../../library/decimal.rst:1482 msgid "" "The sign of the result, if non-zero, is the same as that of the original " "dividend." msgstr "" +"結果的符號(如果非零)與原始被除數的符號相同。" #: ../../library/decimal.rst:1488 msgid "" "Returns ``x - y * n``, where *n* is the integer nearest the exact value of " "``x / y`` (if the result is 0 then its sign will be the sign of *x*)." msgstr "" +"返回 ``x - y * n``,其中 *n* 是最接近 ``x / y`` 精確值的整數(如果" +"結果是 0,則其符號將是 *x* 的符號)。" #: ../../library/decimal.rst:1494 msgid "Returns a rotated copy of *x*, *y* times." msgstr "" +"返回 *x* 的旋轉副本,旋轉 *y* 次。" #: ../../library/decimal.rst:1499 msgid "Returns ``True`` if the two operands have the same exponent." msgstr "" +"如果兩個運算元具有相同的指數則返回 ``True``。" #: ../../library/decimal.rst:1504 msgid "Returns the first operand after adding the second value its exp." msgstr "" +"返回第一個運算元在加上第二個值的 exp 後的結果。" #: ../../library/decimal.rst:1509 msgid "Returns a shifted copy of *x*, *y* times." msgstr "" +"返回 *x* 的移位副本,移位 *y* 次。" #: ../../library/decimal.rst:1514 msgid "Square root of a non-negative number to context precision." msgstr "" +"非負數在 context 精度下的平方根。" #: ../../library/decimal.rst:1519 msgid "Return the difference between *x* and *y*." msgstr "" +"返回 *x* 和 *y* 的差。" #: ../../library/decimal.rst:1533 msgid "Rounds to an integer." msgstr "" +"將位為整數。" #: ../../library/decimal.rst:1538 msgid "Converts a number to a string using scientific notation." msgstr "" +"使用科學記號法將數字轉換為字串。" #: ../../library/decimal.rst:1545 msgid "Constants" @@ -1941,6 +2396,7 @@ msgid "" "The constants in this section are only relevant for the C module. They are " "also included in the pure Python version for compatibility." msgstr "" +"本節中的常數僅與 C 模組相關。為了相容性,它們也包含在純 Python 版本中。" #: ../../library/decimal.rst:1551 msgid "32-bit" @@ -1978,6 +2434,7 @@ msgstr "``-1999999999999999997``" msgid "" "The value is ``True``. Deprecated, because Python now always has threads." msgstr "" +"值是 ``True``。已棄用,因為 Python 現在總是有執行緒。" #: ../../library/decimal.rst:1571 msgid "" @@ -1987,54 +2444,60 @@ msgid "" "value is ``False``. This is slightly faster in some nested context " "scenarios." msgstr "" +"預設值是 ``True``。如果 Python 是使用 :option:`--without-decimal-contextvar " +"選項 <--without-decimal-contextvar>` 配置的,C 版本使用執行緒區域而非協程區域 " +"context,且值為 ``False``。在某些巢狀 context 情境中這稍微快一些。" #: ../../library/decimal.rst:1580 msgid "Rounding modes" -msgstr "" +msgstr "捨入模式" #: ../../library/decimal.rst:1584 msgid "Round towards ``Infinity``." -msgstr "" +msgstr "向 ``Infinity`` 捨入。" #: ../../library/decimal.rst:1588 msgid "Round towards zero." -msgstr "" +msgstr "向零捨入。" #: ../../library/decimal.rst:1592 msgid "Round towards ``-Infinity``." -msgstr "" +msgstr "向 ``-Infinity`` 捨入。" #: ../../library/decimal.rst:1596 msgid "Round to nearest with ties going towards zero." -msgstr "" +msgstr "捨入到最近值,平局時向零捨入。" #: ../../library/decimal.rst:1600 msgid "Round to nearest with ties going to nearest even integer." -msgstr "" +msgstr "捨入到最近值,平局時向最近的偶數捨入。" #: ../../library/decimal.rst:1604 msgid "Round to nearest with ties going away from zero." -msgstr "" +msgstr "捨入到最近值,平局時遠離零捨入。" #: ../../library/decimal.rst:1608 msgid "Round away from zero." -msgstr "" +msgstr "遠離零捨入。" #: ../../library/decimal.rst:1612 msgid "" "Round away from zero if last digit after rounding towards zero would have " "been 0 or 5; otherwise round towards zero." msgstr "" +"如果向零捨入後的最後一位數字為 0 或 5,則遠離零捨入;否則向零捨入。" #: ../../library/decimal.rst:1619 msgid "Signals" -msgstr "" +msgstr "訊號" #: ../../library/decimal.rst:1621 msgid "" "Signals represent conditions that arise during computation. Each corresponds " "to one context flag and one context trap enabler." msgstr "" +"訊號代表在計算過程中產生的條件。每個訊號對應一個情境旗標和一個情境陷阱" +"啟用器。" #: ../../library/decimal.rst:1624 msgid "" @@ -2043,6 +2506,8 @@ msgid "" "to determine whether a computation was exact). After checking the flags, be " "sure to clear all flags before starting the next computation." msgstr "" +"每當遇到條件時,情境旗標就會被設定。計算後,可以檢查旗標以獲取資訊(例如," +"確定計算是否精確)。檢查旗標後,請確保在開始下一次計算之前清除所有旗標。" #: ../../library/decimal.rst:1629 msgid "" @@ -2051,10 +2516,13 @@ msgid "" "`DivisionByZero` trap is set, then a :exc:`DivisionByZero` exception is " "raised upon encountering the condition." msgstr "" +"如果為訊號設定了情境的陷阱啟用器,那麼條件會導致引發 Python 例外。例如," +"如果設定了 :class:`DivisionByZero` 陷阱,那麼在遇到條件時會引發 :exc:" +"`DivisionByZero` 例外。" #: ../../library/decimal.rst:1637 msgid "Altered an exponent to fit representation constraints." -msgstr "" +msgstr "更改指數以符合表示限制。" #: ../../library/decimal.rst:1639 msgid "" @@ -2062,14 +2530,16 @@ msgid "" "attr:`~Context.Emin` and :attr:`~Context.Emax` limits. If possible, the " "exponent is reduced to fit by adding zeros to the coefficient." msgstr "" +"通常,當指數超出情境的 :attr:`~Context.Emin` 和 :attr:`~Context.Emax` 限制時," +"會發生夾制。如果可能的話,透過在係數中新增零來縮小指數以符合限制。" #: ../../library/decimal.rst:1646 msgid "Base class for other signals and a subclass of :exc:`ArithmeticError`." -msgstr "" +msgstr "其他訊號的基底類別,也是 :exc:`ArithmeticError` 的子類別。" #: ../../library/decimal.rst:1651 msgid "Signals the division of a non-infinite number by zero." -msgstr "" +msgstr "發出非無限數被零除的訊號。" #: ../../library/decimal.rst:1653 msgid "" @@ -2077,10 +2547,12 @@ msgid "" "negative power. If this signal is not trapped, returns ``Infinity`` or ``-" "Infinity`` with the sign determined by the inputs to the calculation." msgstr "" +"可能發生在除法、模除法或將數字提升到負次方時。如果此訊號未被捕捉,回傳 " +"``Infinity`` 或 ``-Infinity``,符號由計算的輸入決定。" #: ../../library/decimal.rst:1660 msgid "Indicates that rounding occurred and the result is not exact." -msgstr "" +msgstr "指示發生了捨入且結果不精確。" #: ../../library/decimal.rst:1662 msgid "" @@ -2088,16 +2560,19 @@ msgid "" "result is returned. The signal flag or trap is used to detect when results " "are inexact." msgstr "" +"當捨入過程中丟棄非零數字時發出訊號。回傳捨入結果。訊號旗標或陷阱用於檢測" +"結果何時不精確。" #: ../../library/decimal.rst:1669 msgid "An invalid operation was performed." -msgstr "" +msgstr "執行了無效的運算。" #: ../../library/decimal.rst:1671 msgid "" "Indicates that an operation was requested that does not make sense. If not " "trapped, returns ``NaN``. Possible causes include::" msgstr "" +"指示請求了不合理的運算。如果未被捕捉,回傳 ``NaN``。可能的原因包括: ::" #: ../../library/decimal.rst:1674 msgid "" @@ -2123,7 +2598,7 @@ msgstr "" #: ../../library/decimal.rst:1687 msgid "Numerical overflow." -msgstr "" +msgstr "數值溢位。" #: ../../library/decimal.rst:1689 msgid "" @@ -2133,10 +2608,13 @@ msgid "" "outward to ``Infinity``. In either case, :class:`Inexact` and :class:" "`Rounded` are also signaled." msgstr "" +"指示在捨入發生後指數大於 :attr:`Context.Emax`。如果未被捕捉,結果取決於捨入" +"模式,要麼向內拉到最大可表示的有限數,要麼向外捨入到 ``Infinity``。在任何" +"情況下,:class:`Inexact` 和 :class:`Rounded` 也會發出訊號。" #: ../../library/decimal.rst:1698 msgid "Rounding occurred though possibly no information was lost." -msgstr "" +msgstr "發生了捨入,但可能沒有遺失資訊。" #: ../../library/decimal.rst:1700 msgid "" @@ -2144,30 +2622,38 @@ msgid "" "(such as rounding ``5.00`` to ``5.0``). If not trapped, returns the result " "unchanged. This signal is used to detect loss of significant digits." msgstr "" +"當將位丟棄數字時發出訊號;即使這些數字是零(例如將 ``5.00`` 將位為" +"``5.0``)。如果沒有被捕獲,則返回不變的結果。此訊號用於檢測有效數字的遺失。" #: ../../library/decimal.rst:1708 msgid "Exponent was lower than :attr:`~Context.Emin` prior to rounding." msgstr "" +"在將位之前指數低於 :attr:`~Context.Emin`。" #: ../../library/decimal.rst:1710 msgid "" "Occurs when an operation result is subnormal (the exponent is too small). If " "not trapped, returns the result unchanged." msgstr "" +"當運算結果是次正規(指數太小)時發生。如果沒有被捕獲,則返回不變的結果。" #: ../../library/decimal.rst:1716 msgid "Numerical underflow with result rounded to zero." msgstr "" +"數值下溢,結果將位為零。" #: ../../library/decimal.rst:1718 msgid "" "Occurs when a subnormal result is pushed to zero by rounding. :class:" "`Inexact` and :class:`Subnormal` are also signaled." msgstr "" +"當次正規結果被將位推向零時發生。:class:`Inexact` 和 :class:`Subnormal` " +"也會發出訊號。" #: ../../library/decimal.rst:1724 msgid "Enable stricter semantics for mixing floats and Decimals." msgstr "" +"啟用混合 float 和 Decimal 的更嚴格語意。" #: ../../library/decimal.rst:1726 msgid "" @@ -2179,6 +2665,11 @@ msgid "" "conversions with :meth:`~decimal.Decimal.from_float` or :meth:`~decimal." "Context.create_decimal_from_float` do not set the flag." msgstr "" +"如果訊號沒有被捕獲(預設),則在 :class:`~decimal.Decimal` 建構子、:meth:`~decimal." +"Context.create_decimal` 和所有比較運算子中允許混合 float 和 Decimal。轉換和比較都是" +"精確的。任何混合運算的發生都會透過在 context 標誌中設定 :exc:`FloatOperation` 來" +"默默記錄。使用 :meth:`~decimal.Decimal.from_float` 或 :meth:`~decimal.Context." +"create_decimal_from_float` 的明確轉換不會設定標誌。" #: ../../library/decimal.rst:1734 msgid "" @@ -2186,10 +2677,13 @@ msgid "" "conversions are silent. All other mixed operations raise :exc:" "`FloatOperation`." msgstr "" +"否則(訊號被捕獲),只有相等比較和明確轉換是安靜的。所有其他混合運算都會" +"引發 :exc:`FloatOperation`。" #: ../../library/decimal.rst:1738 msgid "The following table summarizes the hierarchy of signals::" msgstr "" +"以下表格總結了訊號的階層結構: ::" #: ../../library/decimal.rst:1740 msgid "" @@ -2219,11 +2713,11 @@ msgstr "" #: ../../library/decimal.rst:1759 msgid "Floating-point notes" -msgstr "" +msgstr "浮點數注意事項" #: ../../library/decimal.rst:1763 msgid "Mitigating round-off error with increased precision" -msgstr "" +msgstr "透過增加精度來減輕捨入誤差" #: ../../library/decimal.rst:1765 msgid "" @@ -2232,6 +2726,8 @@ msgid "" "can still incur round-off error when non-zero digits exceed the fixed " "precision." msgstr "" +"使用十進位浮點數消除了十進位表示誤差(使得可以精確表示 ``0.1``);然而,當" +"非零數字超過固定精度時,某些運算仍然可能產生捨入誤差。" #: ../../library/decimal.rst:1769 msgid "" @@ -2241,6 +2737,9 @@ msgid "" "floating-point arithmetic with insufficient precision causes the breakdown " "of the associative and distributive properties of addition:" msgstr "" +"捨入誤差的影響可能會因為幾乎抵消的數量的加法或減法而被放大,導致有效位數的" +"損失。Knuth 提供了兩個教學範例,其中精度不足的捨入浮點運算導致加法的結合" +"律和分配律失效:" #: ../../library/decimal.rst:1775 msgid "" @@ -2260,12 +2759,28 @@ msgid "" ">>> u * (v+w)\n" "Decimal('0.0060000')" msgstr "" +"# 來自 Seminumerical Algorithms 第 4.2.2 節的範例。\n" +">>> from decimal import Decimal, getcontext\n" +">>> getcontext().prec = 8\n" +"\n" +">>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')\n" +">>> (u + v) + w\n" +"Decimal('9.5111111')\n" +">>> u + (v + w)\n" +"Decimal('10')\n" +"\n" +">>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')\n" +">>> (u*v) + (u*w)\n" +"Decimal('0.01')\n" +">>> u * (v+w)\n" +"Decimal('0.0060000')" #: ../../library/decimal.rst:1793 msgid "" "The :mod:`decimal` module makes it possible to restore the identities by " "expanding the precision sufficiently to avoid loss of significance:" msgstr "" +":mod:`decimal` 模組透過充分擴展精度以避免有效性損失,使恢復恆等式成為可能:" #: ../../library/decimal.rst:1796 msgid "" @@ -2282,6 +2797,18 @@ msgid "" ">>> u * (v+w)\n" "Decimal('0.0060000')" msgstr "" +">>> getcontext().prec = 20\n" +">>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')\n" +">>> (u + v) + w\n" +"Decimal('9.51111111')\n" +">>> u + (v + w)\n" +"Decimal('9.51111111')\n" +">>>\n" +">>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')\n" +">>> (u*v) + (u*w)\n" +"Decimal('0.0060000')\n" +">>> u * (v+w)\n" +"Decimal('0.0060000')" #: ../../library/decimal.rst:1813 msgid "Special values" @@ -2293,6 +2820,8 @@ msgid "" "including ``NaN``, ``sNaN``, ``-Infinity``, ``Infinity``, and two zeros, " "``+0`` and ``-0``." msgstr "" +":mod:`decimal` 模組的數字系統提供特殊值,包括 ``NaN``、``sNaN``、" +"``-Infinity``、``Infinity`` 和兩個零:``+0`` 和 ``-0``。" #: ../../library/decimal.rst:1819 msgid "" @@ -2302,6 +2831,9 @@ msgid "" "infinity can result from rounding beyond the limits of the largest " "representable number." msgstr "" +"無窮大可以直接透過 ``Decimal('Infinity')`` 建構。此外,當 :exc:`DivisionByZero` " +"訊號未被捕捉時,它們可能來自被零除。同樣地,當 :exc:`Overflow` 訊號未被捕捉時," +"無窮大可能來自超出最大可表示數字限制的捨入。" #: ../../library/decimal.rst:1824 msgid "" @@ -2309,6 +2841,8 @@ msgid "" "where they get treated as very large, indeterminate numbers. For instance, " "adding a constant to infinity gives another infinite result." msgstr "" +"無窮大是有符號的(仿射)並且可以用於算術運算,在那裡它們被視為非常大的不確定" +"數字。例如,將常數加到無窮大會得到另一個無限結果。" #: ../../library/decimal.rst:1828 msgid "" @@ -2320,6 +2854,11 @@ msgid "" "series of computations that occasionally have missing inputs --- it allows " "the calculation to proceed while flagging specific results as invalid." msgstr "" +"某些運算是不確定的,會返回 ``NaN``,或者如果 :exc:`InvalidOperation` 訊號被" +"捕獲,則引發例外。例如,``0/0`` 返回 ``NaN``,意思是「非數字」。這種 ``NaN`` " +"是安靜的,一旦建立,就會在其他計算中流動,總是產生另一個 ``NaN``。這種" +"行為對於偶爾有缺失輸入的一系列計算很有用 —— 它允許計算繼續進行," +"同時將特定結果標記為無效。" #: ../../library/decimal.rst:1836 msgid "" @@ -2327,6 +2866,8 @@ msgid "" "operation. This is a useful return value when an invalid result needs to " "interrupt a calculation for special handling." msgstr "" +"一個變體是 ``sNaN``,它在每次運算後發出訊號而不是保持安靜。當無效結果需要" +"中斷計算進行特殊處理時,這是一個有用的返回值。" #: ../../library/decimal.rst:1840 msgid "" @@ -2344,6 +2885,15 @@ msgid "" "standards-compliance, use the :meth:`~Decimal.compare` and :meth:`~Decimal." "compare_signal` methods instead." msgstr "" +"當涉及 ``NaN`` 時,Python 比較運算子的行為可能有點令人驚訝。當其中一個運算元是" +"安靜或發出訊號的 ``NaN`` 時,相等性測試總是返回 :const:`False`(即使在執行 " +"``Decimal('NaN')==Decimal('NaN')`` 時也是如此),而不等性測試總是返回 :const:" +"`True`。嘗試使用任何 ``<``、``<=``、``>`` 或 ``>=`` 運算子比較兩個 Decimal 時," +"如果任一運算元是 ``NaN``,將引發 :exc:`InvalidOperation` 訊號,如果此訊號沒有被" +"捕獲則返回 :const:`False`。請注意,通用十進位算術規格沒有指定直接比較的行為;" +"這些涉及 ``NaN`` 比較的規則取自 IEEE 854 標準(參見第 5.7 節的表 3)。為確保" +"嚴格符合標準,請改用 :meth:`~Decimal.compare` 和 :meth:`~Decimal.compare_signal` " +"方法。" #: ../../library/decimal.rst:1853 msgid "" @@ -2352,6 +2902,8 @@ msgid "" "greater precision. Since their magnitude is zero, both positive and " "negative zeros are treated as equal and their sign is informational." msgstr "" +"帶符號的零可能来自下溢計算。它們保持如果計算以更高精度執行所會產生的" +"符號。由於它們的大小是零,正零和負零都被視為相等,它們的符號是信息性的。" #: ../../library/decimal.rst:1858 msgid "" @@ -2361,10 +2913,13 @@ msgid "" "normalized floating-point representations, it is not immediately obvious " "that the following calculation returns a value equal to zero:" msgstr "" +"除了兩個不同但相等的帶符號零之外,還有各種零的表示方式,它們有不同的精度但" +"值相等。這需要一點時間來適應。對於習慣於標準化浮點表示的眼睛來說,以下計算" +"返回等於零的值並不立即明顯:" #: ../../library/decimal.rst:1873 msgid "Working with threads" -msgstr "" +msgstr "與執行緒協作" #: ../../library/decimal.rst:1875 msgid "" @@ -2373,12 +2928,16 @@ msgid "" "make changes (such as ``getcontext().prec=10``) without interfering with " "other threads." msgstr "" +":func:`getcontext` 函式為每個執行緒存取不同的 :class:`Context` 物件。擁有獨立" +"的執行緒情境意味著執行緒可以進行變更(如 ``getcontext().prec=10``)而不會" +"干擾其他執行緒。" #: ../../library/decimal.rst:1879 msgid "" "Likewise, the :func:`setcontext` function automatically assigns its target " "to the current thread." msgstr "" +"同樣地,:func:`setcontext` 函式會自動將其目標指派給目前執行緒。" #: ../../library/decimal.rst:1882 msgid "" @@ -2386,6 +2945,8 @@ msgid "" "func:`getcontext` will automatically create a new context for use in the " "current thread." msgstr "" +"如果在 :func:`getcontext` 之前沒有呼叫 :func:`setcontext`,那麼 :func:" +"`getcontext` 會自動建立一個新的情境供目前執行緒使用。" #: ../../library/decimal.rst:1886 msgid "" @@ -2395,6 +2956,10 @@ msgid "" "This should be done *before* any threads are started so that there won't be " "a race condition between threads calling :func:`getcontext`. For example::" msgstr "" +"新的 context 是從稱為 *DefaultContext* 的原型 context 複製而來。為了控制預設值" +"使每個執行緒在整個應用程式中使用相同的值,直接修改 *DefaultContext* 物件。這" +"應該在任何執行緒啟動*之前*完成,這樣執行緒之間呼叫 :func:`getcontext` 就不會" +"有競爭條件。例如: ::" #: ../../library/decimal.rst:1892 msgid "" @@ -2411,16 +2976,29 @@ msgid "" "t3.start()\n" " . . ." msgstr "" +"# 為即將啟動的所有執行緒設定應用程式範圍的預設值\n" +"DefaultContext.prec = 12\n" +"DefaultContext.rounding = ROUND_DOWN\n" +"DefaultContext.traps = ExtendedContext.traps.copy()\n" +"DefaultContext.traps[InvalidOperation] = 1\n" +"setcontext(DefaultContext)\n" +"\n" +"# 之後,可以啟動執行緒\n" +"t1.start()\n" +"t2.start()\n" +"t3.start()\n" +" . . ." #: ../../library/decimal.rst:1911 msgid "Recipes" -msgstr "" +msgstr "實用範例" #: ../../library/decimal.rst:1913 msgid "" "Here are a few recipes that serve as utility functions and that demonstrate " "ways to work with the :class:`Decimal` class::" msgstr "" +"以下是一些實用範例,作為工具函式並展示與 :class:`Decimal` 類別協作的方法: ::" #: ../../library/decimal.rst:1916 msgid "" @@ -2570,20 +3148,166 @@ msgid "" " getcontext().prec -= 2\n" " return +s" msgstr "" +"def moneyfmt(value, places=2, curr='', sep=',', dp='.',\n" +" pos='', neg='-', trailneg=''):\n" +" \"\"\"將 Decimal 轉換為金額格式的字串。\n" +"\n" +" places: 小數點後所需的位數\n" +" curr: 符號前的可選貨幣符號(可為空白)\n" +" sep: 可選的分組分隔符號(逗號、句號、空格或空白)\n" +" dp: 小數點指示符(逗號或句號)\n" +" 只有當 places 為零時才指定為空白\n" +" pos: 正數的可選符號:「+」、空格或空白\n" +" neg: 負數的可選符號:「-」、「(」、空格或空白\n" +" trailneg:可選的尾隨負號指示符:「-」、「)」、空格或空白\n" +"\n" +" >>> d = Decimal('-1234567.8901')\n" +" >>> moneyfmt(d, curr='$')\n" +" '-$1,234,567.89'\n" +" >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')\n" +" '1.234.568-'\n" +" >>> moneyfmt(d, curr='$', neg='(', trailneg=')')\n" +" '($1,234,567.89)'\n" +" >>> moneyfmt(Decimal(123456789), sep=' ')\n" +" '123 456 789.00'\n" +" >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')\n" +" '<0.02>'\n" +"\n" +" \"\"\"\n" +" q = Decimal(10) ** -places # 2 位 --> '0.01'\n" +" sign, digits, exp = value.quantize(q).as_tuple()\n" +" result = []\n" +" digits = list(map(str, digits))\n" +" build, next = result.append, digits.pop\n" +" if sign:\n" +" build(trailneg)\n" +" for i in range(places):\n" +" build(next() if digits else '0')\n" +" if places:\n" +" build(dp)\n" +" if not digits:\n" +" build('0')\n" +" i = 0\n" +" while digits:\n" +" build(next())\n" +" i += 1\n" +" if i == 3 and digits:\n" +" i = 0\n" +" build(sep)\n" +" build(curr)\n" +" build(neg if sign else pos)\n" +" return ''.join(reversed(result))\n" +"\n" +"def pi():\n" +" \"\"\"計算當前精度的 Pi 值。\n" +"\n" +" >>> print(pi())\n" +" 3.141592653589793238462643383\n" +"\n" +" \"\"\"\n" +" getcontext().prec += 2 # 中間步驟的額外位數\n" +" three = Decimal(3) # 對於一般浮點數,替換為 \"three=3.0\"\n" +" lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24\n" +" while s != lasts:\n" +" lasts = s\n" +" n, na = n+na, na+8\n" +" d, da = d+da, da+32\n" +" t = (t * n) / d\n" +" s += t\n" +" getcontext().prec -= 2\n" +" return +s # 一元正號套用新精度\n" +"\n" +"def exp(x):\n" +" \"\"\"回傳 e 的 x 次方。結果型別與輸入型別匹配。\n" +"\n" +" >>> print(exp(Decimal(1)))\n" +" 2.718281828459045235360287471\n" +" >>> print(exp(Decimal(2)))\n" +" 7.389056098930650227230427461\n" +" >>> print(exp(2.0))\n" +" 7.38905609893\n" +" >>> print(exp(2+0j))\n" +" (7.38905609893+0j)\n" +"\n" +" \"\"\"\n" +" getcontext().prec += 2\n" +" i, lasts, s, fact, num = 0, 0, 1, 1, 1\n" +" while s != lasts:\n" +" lasts = s\n" +" i += 1\n" +" fact *= i\n" +" num *= x\n" +" s += num / fact\n" +" getcontext().prec -= 2\n" +" return +s\n" +"\n" +"def cos(x):\n" +" \"\"\"回傳以弧度為單位測量的 x 的餘弦值。\n" +"\n" +" 泰勒級數近似對於較小的 x 值效果最佳。\n" +" 對於較大的值,首先計算 x = x % (2 * pi)。\n" +"\n" +" >>> print(cos(Decimal('0.5')))\n" +" 0.8775825618903727161162815826\n" +" >>> print(cos(0.5))\n" +" 0.87758256189\n" +" >>> print(cos(0.5+0j))\n" +" (0.87758256189+0j)\n" +"\n" +" \"\"\"\n" +" getcontext().prec += 2\n" +" i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1\n" +" while s != lasts:\n" +" lasts = s\n" +" i += 2\n" +" fact *= i * (i-1)\n" +" num *= x * x\n" +" sign *= -1\n" +" s += num / fact * sign\n" +" getcontext().prec -= 2\n" +" return +s\n" +"\n" +"def sin(x):\n" +" \"\"\"回傳以弧度為單位測量的 x 的正弦值。\n" +"\n" +" 泰勒級數近似對於較小的 x 值效果最佳。\n" +" 對於較大的值,首先計算 x = x % (2 * pi)。\n" +"\n" +" >>> print(sin(Decimal('0.5')))\n" +" 0.4794255386042030002732879352\n" +" >>> print(sin(0.5))\n" +" 0.479425538604\n" +" >>> print(sin(0.5+0j))\n" +" (0.479425538604+0j)\n" +"\n" +" \"\"\"\n" +" getcontext().prec += 2\n" +" i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1\n" +" while s != lasts:\n" +" lasts = s\n" +" i += 2\n" +" fact *= i * (i-1)\n" +" num *= x * x\n" +" sign *= -1\n" +" s += num / fact * sign\n" +" getcontext().prec -= 2\n" +" return +s" #: ../../library/decimal.rst:2068 msgid "Decimal FAQ" -msgstr "" +msgstr "Decimal 常見問題" #: ../../library/decimal.rst:2070 msgid "" "Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way " "to minimize typing when using the interactive interpreter?" msgstr "" +"問:輸入 ``decimal.Decimal('1234.5')`` 很麻煩。在使用互動式直譯器時有沒有" +"減少輸入的方法?" #: ../../library/decimal.rst:2073 msgid "A. Some users abbreviate the constructor to just a single letter:" -msgstr "" +msgstr "答:一些使用者將建構函式縮寫為單個字母:" #: ../../library/decimal.rst:2079 msgid "" @@ -2591,6 +3315,8 @@ msgid "" "many places and need to be rounded. Others are not supposed to have excess " "digits and need to be validated. What methods should be used?" msgstr "" +"問:在有兩個小數位的定點應用程式中,一些輸入有很多位數需要捨入。其他輸入" +"不應該有多餘的數字,需要驗證。應該使用什麼方法?" #: ../../library/decimal.rst:2083 msgid "" @@ -2598,12 +3324,15 @@ msgid "" "places. If the :const:`Inexact` trap is set, it is also useful for " "validation:" msgstr "" +"答::meth:`~Decimal.quantize` 方法捨入到固定的小數位數。如果設定了 :const:" +"`Inexact` 陷阱,它也對驗證很有用:" #: ../../library/decimal.rst:2101 msgid "" "Q. Once I have valid two place inputs, how do I maintain that invariant " "throughout an application?" msgstr "" +"問:一旦我有了有效的兩位輸入,我如何在整個應用程式中維持這個不變量?" #: ../../library/decimal.rst:2104 msgid "" @@ -2612,12 +3341,15 @@ msgid "" "division and non-integer multiplication, will change the number of decimal " "places and need to be followed-up with a :meth:`~Decimal.quantize` step:" msgstr "" +"答:像加法、減法和整數乘法這樣的運算會自動保持定點。其他運算,如除法和非整數" +"乘法,會改變小數位數,需要用 :meth:`~Decimal.quantize` 步驟跟進:" #: ../../library/decimal.rst:2122 msgid "" "In developing fixed-point applications, it is convenient to define functions " "to handle the :meth:`~Decimal.quantize` step:" msgstr "" +"在開發定點應用程式時,定義函式來處理 :meth:`~Decimal.quantize` 步驟很方便:" #: ../../library/decimal.rst:2136 msgid "" @@ -2626,16 +3358,19 @@ msgid "" "precisions. Is there a way to transform them to a single recognizable " "canonical value?" msgstr "" +"問:有很多方式表達相同的值。數字 ``200``、``200.000``、``2E2`` 和 ``.02E+4`` " +"在不同精度下都有相同的值。有沒有辦法將它們轉換為單一可識別的標準值?" #: ../../library/decimal.rst:2141 msgid "" "A. The :meth:`~Decimal.normalize` method maps all equivalent values to a " "single representative:" msgstr "" +"答::meth:`~Decimal.normalize` 方法將所有等價值映射到單一代表:" #: ../../library/decimal.rst:2148 msgid "Q. When does rounding occur in a computation?" -msgstr "" +msgstr "問:在計算中什麼時候發生捨入?" #: ../../library/decimal.rst:2150 msgid "" @@ -2646,6 +3381,9 @@ msgid "" "rounding (or other context operations) is applied to the *result* of the " "computation::" msgstr "" +"答:它發生在計算 *之後*。decimal 規範的理念是數字被視為精確的,並且獨立於" +"目前情境而建立。它們甚至可以比目前情境具有更高的精度。計算使用這些精確的" +"輸入進行處理,然後將捨入(或其他情境運算)應用於計算的 *結果*: ::" #: ../../library/decimal.rst:2157 msgid "" @@ -2660,12 +3398,23 @@ msgid "" ">>> pi + 0 - Decimal('0.00005'). # Intermediate values are rounded\n" "Decimal('3.1416')" msgstr "" +">>> getcontext().prec = 5\n" +">>> pi = Decimal('3.1415926535') # 超過 5 位數\n" +">>> pi # 保留所有數字\n" +"Decimal('3.1415926535')\n" +">>> pi + 0 # 加法後捨入\n" +"Decimal('3.1416')\n" +">>> pi - Decimal('0.00005') # 減去未捨入的數字,然後捨入\n" +"Decimal('3.1415')\n" +">>> pi + 0 - Decimal('0.00005'). # 中間值被捨入\n" +"Decimal('3.1416')" #: ../../library/decimal.rst:2168 msgid "" "Q. Some decimal values always print with exponential notation. Is there a " "way to get a non-exponential representation?" msgstr "" +"Q. 某些 decimal 值總是以指數記號列印。有辦法取得非指數表示法嗎?" #: ../../library/decimal.rst:2171 msgid "" @@ -2674,6 +3423,8 @@ msgid "" "``5.0E+3`` as ``5000`` keeps the value constant but cannot show the " "original's two-place significance." msgstr "" +"A. 對於某些值,指數記號是表示係數中有效位數數量的唯一方法。例如,將 " +"``5.0E+3`` 表示為 ``5000`` 保持值不變,但無法顯示原始的兩位有效性。" #: ../../library/decimal.rst:2176 msgid "" @@ -2681,10 +3432,13 @@ msgid "" "remove the exponent and trailing zeroes, losing significance, but keeping " "the value unchanged:" msgstr "" +"如果應用程式不關心追蹤有效性,很容易移除指數和尾隨零,遺失有效性," +"但保持值不變:" #: ../../library/decimal.rst:2186 msgid "Q. Is there a way to convert a regular float to a :class:`Decimal`?" msgstr "" +"Q. 有辦法將一般 float 轉換為 :class:`Decimal` 嗎?" #: ../../library/decimal.rst:2188 msgid "" @@ -2692,6 +3446,8 @@ msgid "" "Decimal though an exact conversion may take more precision than intuition " "would suggest:" msgstr "" +"A. 是的,任何二進位浮點數都可以精確表示為 Decimal,儘管精確轉換可能需要比" +"直覺所暗示的更高精度:" #: ../../library/decimal.rst:2192 msgid "" @@ -2706,6 +3462,7 @@ msgid "" "Q. Within a complex calculation, how can I make sure that I haven't gotten a " "spurious result because of insufficient precision or rounding anomalies." msgstr "" +"Q. 在複雜計算中,我如何確保沒有因為精度不足或將位異常而得到虛假結果。" #: ../../library/decimal.rst:2200 msgid "" @@ -2714,6 +3471,9 @@ msgid "" "Widely differing results indicate insufficient precision, rounding mode " "issues, ill-conditioned inputs, or a numerically unstable algorithm." msgstr "" +"A. decimal 模組使得測試結果很容易。最佳做法是使用更高精度和各種將位" +"模式重新執行計算。差異很大的結果表示精度不足、將位模式問題、" +"情況不佳的輸入或數值不穩定的演算法。" #: ../../library/decimal.rst:2205 msgid "" @@ -2721,6 +3481,8 @@ msgid "" "but not to the inputs. Is there anything to watch out for when mixing " "values of different precisions?" msgstr "" +"Q. 我注意到 context 精度會套用於運算結果但不套用於輸入。在混合不同" +"精度的值時有什麼需要注意的嗎?" #: ../../library/decimal.rst:2209 msgid "" @@ -2730,6 +3492,9 @@ msgid "" "disadvantage is that the results can look odd if you forget that the inputs " "haven't been rounded:" msgstr "" +"A. 是的。原則是所有值都被認為是精確的,對這些值的算術運算也是如此。只有結果" +"會被四捨五入。輸入的優點是「你輸入的就是你得到的」。缺點是如果你忘記輸入沒有" +"被四捨五入,結果可能看起來很奇怪:" #: ../../library/decimal.rst:2214 msgid "" @@ -2750,6 +3515,7 @@ msgid "" "The solution is either to increase precision or to force rounding of inputs " "using the unary plus operation:" msgstr "" +"解決方案是增加精度或使用一元加號運算強制輸入將位:" #: ../../library/decimal.rst:2225 msgid "" @@ -2757,16 +3523,21 @@ msgid "" ">>> +Decimal('1.23456789') # unary plus triggers rounding\n" "Decimal('1.23')" msgstr "" +">>> getcontext().prec = 3\n" +">>> +Decimal('1.23456789') # 一元正號觸發捨入\n" +"Decimal('1.23')" #: ../../library/decimal.rst:2231 msgid "" "Alternatively, inputs can be rounded upon creation using the :meth:`Context." "create_decimal` method:" msgstr "" +"或者,可以使用 :meth:`Context.create_decimal` 方法在建立時將輸入將位:" #: ../../library/decimal.rst:2237 msgid "Q. Is the CPython implementation fast for large numbers?" msgstr "" +"Q. CPython 實作對於大數字快速嗎?" #: ../../library/decimal.rst:2239 msgid "" @@ -2780,6 +3551,12 @@ msgid "" "Discrete_Fourier_transform_(general)#Number-theoretic_transform>`_ for very " "large numbers." msgstr "" +"A. 是的。在 CPython 和 PyPy3 實作中,decimal 模組的 C/CFFI 版本整合了高速" +"`libmpdec `_ 程式庫," +"用於任意精度正確將位的十進位浮點運算 [#]_。``libmpdec`` 對中等大小的" +"數字使用 `Karatsuba 乘法 `_," +"對於非常大的數字使用 `數論變換 `_。" #: ../../library/decimal.rst:2249 msgid "" @@ -2788,12 +3565,16 @@ msgid "" "maximum values, :attr:`~Context.clamp` should always be 0 (the default). " "Setting :attr:`~Context.prec` requires some care." msgstr "" +"context 必須適應精確的任意精度運算。:attr:`~Context.Emin` 和 :attr:" +"`~Context.Emax` 應該始終設定為最大值,:attr:`~Context.clamp` 應該始終" +"為 0(預設)。設定 :attr:`~Context.prec` 需要一些小心。" #: ../../library/decimal.rst:2253 msgid "" "The easiest approach for trying out bignum arithmetic is to use the maximum " "value for :attr:`~Context.prec` as well [#]_::" msgstr "" +"嘗試大數運算的最簡單方法是同時使用 :attr:`~Context.prec` 的最大值 [#]_: ::" #: ../../library/decimal.rst:2256 msgid "" @@ -2812,6 +3593,7 @@ msgid "" "For inexact results, :const:`MAX_PREC` is far too large on 64-bit platforms " "and the available memory will be insufficient::" msgstr "" +"對於不精確的結果,:const:`MAX_PREC` 在 64 位元平台上太大了,可用記憶體將不足: ::" #: ../../library/decimal.rst:2265 msgid "" @@ -2832,6 +3614,9 @@ msgid "" "that you have 8GB of RAM and expect 10 simultaneous operands using a maximum " "of 500MB each::" msgstr "" +"在具有過度分配的系統上(例如 Linux),更精密的方法是將 :attr:`~Context.prec` " +"調整為可用 RAM 的數量。假設你有 8GB 的 RAM,並且預期 10 個同時操作數,每個最多" +"使用 500MB: ::" #: ../../library/decimal.rst:2274 msgid "" @@ -2856,6 +3641,25 @@ msgid "" " File \"\", line 1, in \n" " decimal.Inexact: []" msgstr "" +">>> import sys\n" +">>>\n" +">>> # 單一運算元使用 500MB 8 位元組字元的最大位數\n" +">>> # 每個字元 19 位數(32 位元版本為 4 位元組和 9 位數):\n" +">>> maxdigits = 19 * ((500 * 1024**2) // 8)\n" +">>>\n" +">>> # 檢查這是否有效:\n" +">>> c = Context(prec=maxdigits, Emax=MAX_EMAX, Emin=MIN_EMIN)\n" +">>> c.traps[Inexact] = True\n" +">>> setcontext(c)\n" +">>>\n" +">>> # 用九填滿可用精度:\n" +">>> x = Decimal(0).logical_invert() * 9\n" +">>> sys.getsizeof(x)\n" +"524288112\n" +">>> x + 2\n" +"Traceback (most recent call last):\n" +" File \"\", line 1, in \n" +" decimal.Inexact: []" #: ../../library/decimal.rst:2294 msgid "" @@ -2863,8 +3667,11 @@ msgid "" "recommended to estimate even tighter bounds and set the :attr:`Inexact` trap " "if all calculations are expected to be exact." msgstr "" +"一般來說(特別是在沒有過度分配的系統上),建議估算更緊密的界限並設定 " +":attr:`Inexact` trap,如果所有計算都預期是精確的。" #: ../../library/decimal.rst:2303 msgid "" "This approach now works for all exact results except for non-integer powers." msgstr "" +"這個方法現在對所有精確結果都有效,除了非整數冪次。" pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy