Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

2310

2311

2312

2313

2314

2315

2316

2317

2318

2319

2320

2321

2322

2323

2324

2325

2326

2327

2328

2329

2330

2331

2332

2333

2334

2335

2336

2337

2338

2339

2340

2341

2342

2343

2344

2345

2346

2347

2348

2349

2350

2351

2352

2353

2354

2355

2356

2357

2358

2359

2360

2361

2362

2363

2364

2365

2366

2367

2368

2369

2370

2371

2372

2373

2374

2375

2376

2377

2378

2379

2380

2381

2382

2383

2384

2385

2386

2387

2388

2389

2390

2391

2392

2393

2394

2395

2396

2397

2398

2399

2400

2401

2402

2403

2404

2405

2406

2407

2408

2409

2410

2411

2412

2413

2414

2415

2416

2417

2418

2419

2420

2421

2422

2423

2424

2425

2426

2427

2428

2429

2430

2431

2432

2433

2434

2435

2436

2437

2438

2439

2440

2441

2442

2443

2444

2445

2446

2447

2448

2449

2450

2451

2452

2453

2454

2455

2456

2457

2458

2459

2460

2461

2462

2463

2464

2465

2466

2467

2468

2469

2470

2471

2472

2473

2474

2475

2476

2477

2478

2479

2480

2481

2482

2483

2484

2485

2486

2487

2488

2489

2490

2491

2492

2493

2494

2495

2496

2497

2498

2499

2500

2501

2502

2503

2504

2505

2506

2507

2508

2509

2510

2511

2512

2513

2514

2515

2516

2517

2518

2519

2520

2521

2522

2523

2524

2525

2526

2527

2528

2529

2530

2531

2532

2533

2534

2535

2536

2537

2538

2539

2540

2541

2542

2543

2544

2545

2546

2547

2548

2549

2550

2551

2552

2553

2554

2555

2556

2557

2558

2559

2560

2561

2562

2563

2564

2565

2566

2567

2568

2569

2570

2571

2572

2573

2574

2575

2576

2577

2578

2579

2580

2581

2582

2583

2584

2585

2586

2587

2588

2589

2590

2591

2592

2593

2594

2595

2596

2597

2598

2599

2600

2601

2602

2603

2604

2605

2606

2607

2608

2609

2610

2611

2612

2613

2614

2615

2616

2617

2618

2619

2620

2621

2622

2623

2624

2625

2626

2627

2628

2629

2630

2631

2632

2633

2634

2635

2636

2637

2638

2639

2640

2641

2642

2643

2644

2645

2646

2647

2648

2649

2650

2651

2652

2653

2654

2655

2656

2657

2658

2659

2660

2661

2662

2663

2664

2665

2666

2667

2668

2669

2670

2671

2672

2673

2674

2675

2676

2677

2678

2679

2680

2681

2682

2683

2684

2685

2686

2687

2688

2689

2690

2691

2692

2693

2694

2695

2696

2697

2698

2699

2700

2701

2702

2703

2704

2705

2706

2707

2708

2709

2710

2711

2712

2713

2714

2715

2716

2717

2718

2719

2720

2721

2722

2723

2724

2725

2726

2727

2728

2729

2730

2731

2732

2733

2734

2735

2736

2737

2738

2739

2740

2741

2742

2743

2744

2745

2746

2747

2748

2749

2750

2751

2752

2753

2754

2755

2756

2757

2758

2759

2760

2761

2762

2763

2764

2765

2766

2767

2768

2769

2770

2771

2772

2773

2774

2775

2776

2777

2778

2779

2780

2781

2782

2783

2784

2785

2786

2787

2788

2789

2790

2791

2792

2793

2794

2795

2796

2797

2798

2799

2800

2801

2802

2803

2804

2805

2806

2807

2808

2809

2810

2811

2812

2813

2814

2815

2816

2817

2818

2819

2820

2821

2822

2823

2824

2825

2826

2827

2828

2829

2830

2831

2832

2833

2834

2835

2836

2837

2838

2839

2840

2841

2842

2843

2844

2845

2846

2847

2848

2849

2850

2851

2852

2853

2854

2855

2856

2857

2858

2859

2860

2861

2862

2863

2864

2865

2866

2867

2868

2869

2870

2871

2872

2873

2874

2875

2876

2877

2878

2879

2880

2881

2882

2883

2884

2885

2886

2887

2888

2889

2890

2891

2892

2893

2894

2895

2896

2897

2898

2899

2900

2901

2902

2903

2904

2905

2906

2907

2908

2909

2910

2911

2912

2913

2914

2915

2916

2917

2918

2919

2920

2921

2922

2923

2924

2925

2926

2927

2928

2929

2930

2931

2932

2933

2934

2935

2936

2937

2938

2939

2940

2941

2942

2943

2944

2945

2946

2947

2948

2949

2950

2951

2952

2953

2954

2955

2956

2957

2958

2959

2960

2961

2962

2963

2964

2965

2966

2967

2968

2969

2970

2971

2972

2973

2974

2975

2976

2977

2978

2979

2980

2981

2982

2983

2984

2985

2986

2987

2988

2989

2990

2991

2992

2993

2994

2995

2996

2997

2998

2999

3000

3001

3002

3003

3004

3005

3006

3007

3008

3009

3010

3011

3012

3013

3014

3015

3016

3017

3018

3019

3020

3021

3022

3023

3024

3025

3026

3027

3028

3029

3030

3031

3032

3033

3034

3035

3036

3037

3038

3039

3040

3041

3042

3043

3044

3045

3046

3047

3048

3049

3050

3051

3052

3053

3054

3055

3056

3057

3058

3059

3060

3061

3062

3063

3064

3065

3066

3067

3068

3069

3070

3071

3072

3073

3074

3075

3076

3077

3078

3079

3080

3081

3082

3083

3084

3085

3086

3087

3088

3089

3090

3091

3092

3093

3094

3095

3096

3097

3098

3099

3100

3101

3102

3103

3104

3105

3106

3107

3108

3109

3110

3111

3112

3113

3114

3115

3116

3117

3118

3119

3120

3121

3122

3123

3124

3125

3126

3127

3128

3129

3130

3131

3132

3133

3134

3135

3136

3137

3138

3139

3140

3141

3142

3143

3144

3145

3146

3147

3148

3149

3150

3151

3152

3153

3154

3155

3156

3157

3158

3159

3160

3161

3162

3163

3164

3165

3166

3167

3168

3169

3170

3171

3172

3173

3174

3175

3176

3177

3178

3179

3180

3181

3182

3183

3184

3185

3186

3187

3188

3189

3190

3191

3192

3193

3194

3195

3196

3197

3198

3199

3200

3201

3202

3203

3204

3205

3206

3207

3208

3209

3210

3211

3212

3213

3214

3215

3216

3217

3218

3219

3220

3221

3222

3223

3224

3225

3226

3227

3228

3229

3230

3231

3232

3233

3234

3235

3236

3237

3238

3239

3240

3241

3242

3243

3244

3245

3246

3247

3248

3249

3250

3251

3252

3253

3254

3255

3256

3257

3258

3259

3260

3261

3262

3263

3264

3265

3266

3267

3268

3269

3270

3271

3272

3273

3274

3275

3276

3277

3278

3279

3280

3281

3282

3283

3284

3285

3286

3287

3288

3289

3290

3291

3292

3293

3294

3295

3296

3297

3298

3299

3300

3301

3302

3303

3304

3305

3306

3307

3308

3309

3310

3311

3312

3313

3314

3315

3316

3317

3318

3319

3320

3321

3322

3323

3324

3325

3326

3327

3328

3329

3330

3331

3332

3333

3334

3335

3336

3337

3338

3339

3340

3341

3342

3343

3344

3345

3346

3347

3348

3349

3350

3351

3352

3353

3354

3355

3356

3357

3358

3359

3360

3361

3362

3363

3364

3365

3366

3367

3368

3369

3370

3371

3372

3373

3374

3375

3376

3377

3378

3379

3380

3381

3382

3383

3384

3385

3386

3387

3388

3389

3390

3391

3392

3393

3394

3395

3396

3397

3398

3399

3400

3401

3402

3403

3404

3405

3406

3407

3408

3409

3410

3411

3412

3413

3414

3415

3416

3417

3418

3419

3420

3421

3422

3423

3424

3425

3426

3427

3428

3429

3430

3431

3432

3433

3434

3435

3436

3437

3438

3439

3440

3441

3442

3443

3444

3445

3446

3447

3448

3449

3450

3451

3452

3453

3454

3455

3456

3457

3458

3459

3460

3461

3462

3463

3464

3465

3466

3467

3468

3469

3470

3471

3472

3473

3474

3475

3476

3477

3478

3479

3480

3481

3482

3483

3484

3485

3486

3487

3488

3489

3490

3491

3492

3493

3494

3495

3496

3497

3498

3499

3500

3501

3502

3503

3504

3505

3506

3507

3508

3509

3510

3511

3512

3513

3514

3515

3516

3517

3518

3519

3520

3521

3522

3523

3524

3525

3526

3527

3528

3529

3530

3531

3532

3533

3534

3535

3536

3537

3538

3539

3540

3541

3542

3543

3544

3545

3546

3547

3548

3549

3550

3551

3552

3553

3554

3555

3556

3557

3558

3559

3560

3561

3562

3563

3564

3565

3566

3567

3568

3569

3570

3571

3572

3573

3574

3575

3576

3577

3578

3579

3580

3581

3582

3583

3584

3585

3586

3587

3588

3589

3590

3591

3592

3593

3594

3595

3596

3597

3598

3599

3600

3601

3602

3603

3604

3605

3606

3607

3608

3609

3610

3611

3612

3613

3614

3615

3616

3617

3618

3619

3620

3621

3622

3623

3624

3625

3626

3627

3628

3629

3630

3631

3632

3633

3634

3635

3636

3637

3638

3639

3640

3641

3642

3643

3644

3645

3646

3647

3648

3649

3650

3651

3652

3653

3654

3655

3656

3657

3658

3659

3660

3661

3662

3663

3664

3665

3666

3667

3668

3669

3670

3671

3672

3673

3674

3675

3676

3677

3678

3679

3680

3681

3682

3683

3684

3685

3686

3687

3688

3689

3690

3691

3692

3693

3694

3695

3696

3697

3698

3699

3700

3701

3702

3703

3704

3705

3706

3707

3708

3709

3710

3711

3712

3713

3714

3715

3716

3717

3718

3719

3720

3721

3722

3723

3724

3725

3726

3727

3728

3729

3730

3731

3732

3733

3734

3735

3736

3737

3738

3739

3740

3741

3742

3743

3744

3745

3746

3747

3748

3749

3750

3751

3752

3753

3754

3755

3756

3757

3758

3759

3760

3761

3762

3763

3764

3765

3766

3767

3768

3769

3770

3771

3772

3773

3774

3775

3776

3777

3778

3779

3780

3781

3782

3783

3784

3785

3786

3787

3788

3789

3790

3791

3792

3793

3794

3795

3796

3797

3798

3799

3800

3801

3802

3803

3804

3805

3806

3807

3808

3809

3810

3811

3812

3813

3814

3815

3816

3817

3818

3819

3820

3821

3822

3823

3824

3825

3826

3827

3828

3829

3830

3831

3832

3833

3834

3835

3836

3837

3838

3839

3840

3841

3842

3843

3844

3845

3846

3847

3848

3849

3850

3851

3852

3853

3854

3855

3856

3857

3858

3859

3860

3861

3862

3863

3864

3865

3866

3867

3868

3869

3870

3871

3872

3873

3874

3875

3876

3877

3878

3879

3880

3881

3882

3883

3884

3885

3886

3887

3888

3889

3890

3891

3892

3893

3894

3895

3896

3897

3898

3899

3900

3901

3902

3903

3904

3905

3906

3907

3908

3909

3910

3911

3912

3913

3914

3915

3916

3917

3918

3919

3920

3921

3922

3923

3924

3925

3926

3927

3928

3929

3930

3931

3932

3933

3934

3935

3936

3937

3938

3939

3940

3941

3942

3943

3944

3945

3946

3947

3948

3949

3950

3951

3952

3953

3954

3955

3956

3957

3958

3959

3960

3961

3962

3963

3964

3965

3966

3967

3968

3969

3970

3971

3972

3973

3974

3975

3976

3977

3978

3979

3980

3981

3982

3983

3984

3985

3986

3987

3988

3989

3990

3991

3992

3993

3994

3995

3996

3997

3998

3999

4000

4001

4002

4003

4004

4005

4006

4007

4008

4009

4010

4011

4012

4013

4014

4015

4016

4017

4018

4019

4020

4021

4022

4023

4024

4025

4026

4027

4028

4029

4030

4031

4032

4033

4034

4035

4036

4037

4038

4039

4040

4041

4042

4043

4044

4045

4046

4047

4048

4049

4050

4051

4052

4053

4054

4055

4056

4057

4058

4059

4060

4061

4062

4063

4064

4065

4066

4067

4068

4069

4070

4071

4072

4073

4074

4075

4076

4077

4078

4079

4080

4081

4082

4083

4084

4085

4086

4087

4088

4089

4090

4091

4092

4093

4094

4095

4096

4097

4098

4099

4100

4101

4102

4103

4104

4105

4106

4107

4108

4109

4110

4111

4112

4113

4114

4115

4116

4117

4118

4119

4120

4121

4122

4123

4124

4125

4126

4127

4128

4129

4130

4131

4132

4133

4134

4135

4136

4137

4138

4139

4140

4141

4142

4143

4144

4145

4146

4147

4148

4149

4150

4151

4152

4153

4154

4155

4156

4157

4158

4159

4160

4161

4162

4163

4164

4165

4166

4167

4168

4169

4170

4171

4172

4173

4174

4175

4176

4177

4178

4179

4180

4181

4182

4183

4184

4185

4186

4187

4188

4189

4190

4191

4192

4193

4194

4195

4196

4197

4198

4199

4200

4201

4202

4203

4204

4205

4206

4207

4208

4209

4210

4211

4212

4213

4214

4215

4216

4217

4218

4219

4220

4221

4222

4223

4224

4225

4226

4227

4228

4229

4230

4231

4232

4233

4234

4235

4236

4237

4238

4239

4240

4241

4242

4243

4244

4245

4246

4247

4248

4249

4250

4251

4252

4253

4254

4255

4256

4257

4258

4259

4260

4261

4262

4263

4264

4265

4266

4267

4268

4269

4270

4271

4272

4273

4274

4275

4276

4277

4278

4279

4280

4281

4282

4283

4284

4285

4286

4287

4288

4289

4290

4291

4292

4293

4294

4295

4296

4297

4298

4299

4300

4301

4302

4303

4304

4305

4306

4307

4308

4309

4310

4311

4312

4313

4314

4315

4316

4317

4318

4319

4320

4321

4322

4323

4324

4325

4326

4327

4328

4329

4330

4331

4332

4333

4334

4335

4336

4337

4338

4339

4340

4341

4342

4343

4344

4345

4346

4347

4348

4349

4350

4351

4352

4353

4354

4355

4356

4357

4358

4359

4360

4361

4362

4363

4364

4365

4366

4367

4368

4369

4370

4371

4372

4373

4374

4375

4376

4377

4378

4379

4380

4381

4382

4383

4384

4385

4386

4387

4388

4389

4390

4391

4392

4393

4394

4395

4396

4397

4398

4399

4400

4401

4402

4403

4404

4405

4406

4407

4408

4409

4410

4411

4412

4413

4414

4415

4416

4417

4418

4419

4420

4421

4422

4423

4424

4425

4426

4427

4428

4429

4430

4431

4432

4433

4434

4435

4436

4437

4438

4439

4440

4441

4442

4443

4444

4445

4446

4447

4448

4449

4450

4451

4452

4453

4454

4455

4456

4457

4458

4459

4460

4461

4462

4463

4464

4465

4466

4467

4468

4469

4470

4471

4472

4473

4474

4475

4476

4477

4478

4479

4480

4481

4482

4483

4484

4485

4486

4487

4488

4489

4490

4491

4492

4493

4494

4495

4496

4497

4498

4499

4500

4501

4502

4503

4504

4505

4506

4507

4508

4509

4510

4511

4512

4513

4514

4515

4516

4517

4518

4519

4520

4521

4522

4523

4524

4525

4526

4527

4528

4529

4530

4531

4532

4533

4534

4535

4536

4537

4538

4539

4540

4541

4542

4543

4544

4545

4546

4547

4548

4549

4550

4551

4552

4553

4554

4555

4556

4557

4558

4559

4560

4561

4562

4563

4564

4565

4566

4567

4568

4569

4570

4571

4572

4573

4574

4575

4576

4577

4578

4579

4580

4581

4582

4583

4584

4585

4586

4587

4588

4589

4590

4591

4592

4593

4594

4595

4596

4597

4598

4599

4600

4601

4602

4603

4604

4605

4606

4607

4608

4609

4610

4611

4612

4613

4614

4615

4616

4617

4618

4619

4620

4621

4622

4623

4624

4625

4626

4627

4628

4629

4630

4631

4632

4633

4634

4635

4636

4637

4638

4639

4640

4641

4642

4643

4644

4645

4646

4647

4648

4649

4650

4651

4652

4653

4654

4655

4656

4657

4658

4659

4660

4661

4662

4663

4664

4665

4666

4667

4668

4669

4670

4671

4672

4673

4674

4675

4676

4677

4678

4679

4680

4681

4682

4683

4684

4685

4686

4687

4688

4689

4690

4691

4692

4693

4694

4695

4696

4697

4698

4699

4700

4701

4702

4703

4704

4705

4706

4707

4708

4709

4710

4711

4712

4713

4714

4715

4716

4717

4718

4719

4720

4721

4722

4723

4724

4725

4726

4727

4728

4729

4730

4731

4732

4733

4734

4735

4736

4737

4738

4739

4740

4741

4742

4743

4744

4745

4746

4747

4748

4749

4750

4751

4752

4753

4754

4755

4756

4757

4758

4759

4760

4761

4762

4763

4764

4765

4766

4767

4768

4769

4770

4771

4772

4773

4774

4775

4776

4777

4778

4779

4780

4781

4782

4783

4784

4785

4786

4787

4788

4789

4790

4791

4792

4793

4794

4795

4796

4797

4798

4799

4800

4801

4802

4803

4804

4805

4806

4807

4808

4809

4810

4811

4812

4813

4814

4815

4816

4817

4818

4819

4820

4821

4822

4823

4824

4825

4826

4827

4828

4829

4830

4831

4832

4833

4834

4835

4836

4837

4838

4839

4840

4841

4842

4843

4844

4845

4846

4847

4848

4849

4850

4851

4852

4853

4854

4855

4856

4857

4858

4859

4860

4861

4862

4863

4864

4865

4866

4867

4868

4869

4870

4871

4872

4873

4874

4875

4876

4877

4878

4879

4880

4881

4882

4883

4884

4885

4886

4887

4888

4889

4890

4891

4892

4893

4894

4895

4896

4897

4898

4899

4900

4901

4902

4903

4904

4905

4906

4907

4908

4909

4910

4911

4912

4913

4914

4915

4916

4917

4918

4919

4920

4921

4922

4923

4924

4925

4926

4927

4928

4929

4930

4931

4932

4933

4934

4935

4936

4937

4938

4939

4940

4941

4942

4943

4944

4945

4946

4947

4948

4949

4950

4951

4952

4953

4954

4955

4956

4957

4958

4959

4960

4961

4962

4963

4964

4965

4966

4967

4968

4969

4970

4971

4972

4973

4974

4975

4976

4977

4978

4979

4980

4981

4982

4983

4984

4985

4986

4987

4988

4989

4990

4991

4992

4993

4994

4995

4996

4997

4998

4999

5000

5001

5002

5003

5004

5005

5006

5007

5008

5009

5010

5011

5012

5013

5014

5015

5016

5017

5018

5019

5020

5021

5022

5023

5024

5025

5026

5027

5028

5029

5030

5031

5032

5033

5034

5035

5036

5037

5038

5039

5040

5041

5042

5043

5044

5045

5046

5047

5048

5049

5050

5051

5052

5053

5054

5055

5056

5057

5058

5059

5060

5061

5062

5063

5064

5065

5066

5067

5068

5069

5070

5071

5072

5073

5074

5075

5076

5077

5078

5079

5080

5081

5082

5083

5084

5085

5086

5087

5088

5089

5090

5091

5092

5093

5094

5095

5096

5097

5098

5099

5100

5101

5102

5103

5104

5105

5106

5107

5108

5109

5110

5111

5112

5113

5114

5115

5116

5117

5118

5119

5120

5121

5122

5123

5124

5125

5126

5127

5128

5129

5130

5131

5132

5133

5134

5135

5136

5137

5138

5139

5140

5141

5142

5143

5144

5145

5146

5147

5148

5149

5150

5151

5152

5153

5154

5155

5156

5157

5158

5159

5160

5161

5162

5163

5164

5165

5166

5167

5168

5169

5170

5171

5172

5173

5174

5175

5176

5177

5178

5179

5180

5181

5182

5183

5184

5185

5186

5187

5188

5189

5190

5191

5192

5193

5194

5195

5196

5197

5198

5199

5200

5201

5202

5203

5204

5205

5206

5207

5208

5209

5210

5211

5212

5213

5214

5215

5216

5217

5218

5219

5220

5221

5222

5223

5224

5225

5226

5227

5228

5229

5230

5231

5232

5233

5234

5235

5236

5237

5238

5239

5240

5241

5242

5243

5244

5245

5246

5247

5248

5249

5250

5251

5252

5253

5254

5255

5256

5257

5258

5259

5260

5261

5262

5263

5264

5265

5266

5267

5268

5269

5270

5271

5272

5273

5274

5275

5276

5277

5278

5279

5280

5281

5282

5283

5284

5285

5286

5287

5288

5289

5290

5291

5292

5293

5294

5295

5296

5297

5298

5299

5300

5301

5302

5303

5304

5305

5306

5307

5308

5309

5310

5311

5312

5313

5314

5315

5316

5317

5318

5319

5320

5321

5322

5323

5324

5325

5326

5327

5328

5329

5330

5331

5332

5333

5334

5335

5336

5337

5338

5339

5340

5341

5342

5343

5344

5345

5346

5347

5348

5349

5350

5351

5352

5353

5354

5355

5356

5357

5358

5359

5360

5361

5362

5363

5364

5365

5366

5367

5368

5369

5370

5371

5372

5373

5374

5375

5376

5377

5378

5379

5380

5381

5382

5383

5384

5385

5386

5387

5388

5389

5390

5391

5392

5393

5394

5395

5396

5397

5398

5399

5400

5401

5402

5403

5404

5405

5406

5407

5408

5409

5410

5411

5412

5413

5414

5415

5416

5417

5418

5419

5420

5421

5422

5423

5424

5425

5426

5427

5428

5429

5430

5431

5432

5433

5434

5435

5436

5437

5438

5439

5440

5441

5442

5443

5444

5445

5446

5447

5448

5449

5450

5451

5452

5453

5454

5455

5456

5457

5458

5459

5460

5461

5462

5463

5464

5465

5466

5467

5468

5469

5470

5471

5472

5473

5474

5475

5476

5477

5478

5479

5480

5481

5482

5483

5484

5485

5486

5487

5488

5489

5490

5491

5492

5493

5494

5495

5496

5497

5498

5499

5500

5501

5502

5503

5504

5505

5506

5507

5508

5509

5510

5511

5512

5513

5514

5515

5516

5517

5518

5519

5520

5521

5522

5523

5524

5525

5526

5527

5528

5529

5530

5531

5532

5533

5534

5535

5536

5537

5538

5539

5540

5541

5542

5543

5544

5545

5546

5547

5548

5549

5550

5551

5552

5553

5554

5555

5556

5557

5558

5559

5560

5561

5562

5563

5564

5565

5566

5567

5568

5569

5570

5571

5572

5573

5574

5575

5576

5577

5578

5579

5580

5581

5582

5583

5584

5585

5586

5587

5588

5589

5590

5591

5592

5593

5594

5595

5596

5597

5598

5599

5600

5601

5602

5603

5604

5605

5606

5607

5608

5609

5610

5611

5612

5613

5614

5615

5616

5617

5618

5619

5620

5621

5622

5623

5624

5625

5626

5627

5628

5629

5630

5631

5632

5633

5634

5635

5636

5637

5638

5639

5640

5641

5642

5643

5644

5645

5646

5647

5648

5649

5650

5651

5652

5653

5654

5655

5656

5657

5658

5659

5660

5661

5662

5663

5664

5665

5666

5667

5668

5669

5670

5671

5672

5673

5674

5675

5676

5677

5678

5679

5680

5681

5682

5683

5684

5685

5686

5687

5688

5689

5690

5691

5692

5693

5694

5695

5696

5697

5698

5699

5700

5701

5702

5703

5704

5705

5706

5707

5708

5709

5710

5711

5712

5713

5714

5715

5716

5717

5718

5719

5720

5721

5722

5723

5724

5725

5726

5727

5728

5729

5730

5731

5732

5733

5734

5735

5736

5737

5738

5739

5740

5741

5742

5743

5744

5745

5746

5747

5748

5749

5750

5751

5752

5753

5754

5755

5756

5757

5758

5759

5760

5761

5762

5763

5764

5765

5766

5767

5768

5769

5770

5771

5772

5773

5774

5775

5776

5777

5778

5779

5780

5781

5782

5783

5784

5785

5786

5787

5788

5789

5790

5791

5792

5793

5794

5795

5796

5797

5798

5799

5800

5801

5802

5803

5804

5805

5806

5807

5808

5809

5810

5811

5812

5813

5814

5815

5816

5817

5818

5819

5820

5821

5822

5823

5824

5825

5826

5827

5828

5829

5830

5831

5832

5833

5834

5835

5836

5837

5838

5839

5840

5841

5842

5843

5844

5845

5846

5847

5848

5849

5850

5851

5852

5853

5854

5855

5856

5857

5858

5859

5860

5861

5862

5863

5864

5865

5866

5867

5868

5869

5870

5871

5872

5873

5874

5875

5876

5877

5878

5879

5880

5881

5882

5883

5884

5885

5886

5887

5888

5889

5890

5891

5892

5893

5894

5895

5896

5897

5898

5899

5900

5901

5902

5903

5904

5905

5906

5907

5908

5909

5910

5911

5912

5913

5914

5915

5916

5917

5918

5919

5920

5921

5922

5923

5924

5925

5926

5927

5928

5929

5930

5931

5932

5933

5934

5935

5936

5937

5938

5939

5940

5941

5942

5943

5944

5945

5946

5947

5948

5949

5950

5951

5952

5953

5954

5955

5956

5957

5958

5959

5960

5961

5962

5963

5964

5965

5966

5967

5968

5969

r""" 

Arbitrary Precision Real Numbers 

  

AUTHORS: 

  

- Kyle Schalm (2005-09) 

  

- William Stein: bug fixes, examples, maintenance 

  

- Didier Deshommes (2006-03-19): examples 

  

- David Harvey (2006-09-20): compatibility with Element._parent 

  

- William Stein (2006-10): default printing truncates to avoid base-2 

rounding confusing (fix suggested by Bill Hart) 

  

- Didier Deshommes: special constructor for QD numbers 

  

- Paul Zimmermann (2008-01): added new functions from mpfr-2.3.0, 

replaced some, e.g., sech = 1/cosh, by their original mpfr version. 

  

- Carl Witty (2008-02): define floating-point rank and associated 

functions; add some documentation 

  

- Robert Bradshaw (2009-09): decimal literals, optimizations 

  

- Jeroen Demeyer (2012-05-27): set the MPFR exponent range to the 

maximal possible value (:trac:`13033`) 

  

- Travis Scrimshaw (2012-11-02): Added doctests for full coverage 

  

- Eviatar Bach (2013-06): Fixing numerical evaluation of log_gamma 

  

- Vincent Klein (2017-06): RealNumber constructor support gmpy2.mpfr 

, gmpy2.mpq or gmpy2.mpz parameter. 

Add __mpfr__ to class RealNumber. 

  

This is a binding for the MPFR arbitrary-precision floating point 

library. 

  

We define a class :class:`RealField`, where each instance of 

:class:`RealField` specifies a field of floating-point 

numbers with a specified precision and rounding mode. Individual 

floating-point numbers are of :class:`RealNumber`. 

  

In Sage (as in MPFR), floating-point numbers of precision 

`p` are of the form `s m 2^{e-p}`, where 

`s \in \{-1, 1\}`, `2^{p-1} \leq m < 2^p`, and 

`-2^B + 1 \leq e \leq 2^B - 1` where `B = 30` on 32-bit systems 

and `B = 62` on 64-bit systems; 

additionally, there are the special values ``+0``, ``-0``, 

``+infinity``, ``-infinity`` and ``NaN`` (which stands for Not-a-Number). 

  

Operations in this module which are direct wrappers of MPFR 

functions are "correctly rounded"; we briefly describe what this 

means. Assume that you could perform the operation exactly, on real 

numbers, to get a result `r`. If this result can be 

represented as a floating-point number, then we return that 

number. 

  

Otherwise, the result `r` is between two floating-point 

numbers. For the directed rounding modes (round to plus infinity, 

round to minus infinity, round to zero), we return the 

floating-point number in the indicated direction from `r`. 

For round to nearest, we return the floating-point number which is 

nearest to `r`. 

  

This leaves one case unspecified: in round to nearest mode, what 

happens if `r` is exactly halfway between the two nearest 

floating-point numbers? In that case, we round to the number with 

an even mantissa (the mantissa is the number `m` in the 

representation above). 

  

Consider the ordered set of floating-point numbers of precision 

`p`. (Here we identify ``+0`` and 

``-0``, and ignore ``NaN``.) We can give a 

bijection between these floating-point numbers and a segment of the 

integers, where 0 maps to 0 and adjacent floating-point numbers map 

to adjacent integers. We call the integer corresponding to a given 

floating-point number the "floating-point rank" of the number. 

(This is not standard terminology; I just made it up.) 

  

EXAMPLES: 

  

A difficult conversion:: 

  

sage: RR(sys.maxsize) 

9.22337203685478e18 # 64-bit 

2.14748364700000e9 # 32-bit 

  

TESTS:: 

  

sage: -1e30 

-1.00000000000000e30 

sage: (-1. + 2^-52).hex() 

'-0xf.ffffffffffffp-4' 

  

Make sure we don't have a new field for every new literal:: 

  

sage: parent(2.0) is parent(2.0) 

True 

sage: RealField(100, rnd='RNDZ') is RealField(100, rnd='RNDD') 

False 

sage: RealField(100, rnd='RNDZ') is RealField(100, rnd='RNDZ') 

True 

sage: RealField(100, rnd='RNDZ') is RealField(100, rnd=1) 

True 

""" 

  

#***************************************************************************** 

# Copyright (C) 2005-2006 William Stein <wstein@gmail.com> 

# 

# This program is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 2 of the License, or 

# (at your option) any later version. 

# http://www.gnu.org/licenses/ 

#***************************************************************************** 

  

from __future__ import absolute_import, print_function 

  

import math # for log 

import sys 

import re 

  

from cpython.object cimport Py_NE, Py_EQ 

from cysignals.signals cimport sig_on, sig_off 

  

from sage.ext.stdsage cimport PY_NEW 

from sage.libs.gmp.pylong cimport mpz_set_pylong 

from sage.libs.gmp.mpz cimport * 

from sage.libs.mpfr cimport * 

from sage.misc.randstate cimport randstate, current_randstate 

from sage.cpython.string cimport char_to_str, str_to_bytes 

from sage.misc.superseded import deprecation 

  

from sage.structure.element cimport RingElement, Element, ModuleElement 

from sage.structure.richcmp cimport rich_to_bool_sgn, rich_to_bool 

cdef bin_op 

from sage.structure.element import bin_op 

  

import sage.misc.weak_dict 

  

import operator 

  

from cypari2.paridecl cimport * 

from cypari2.gen cimport Gen 

from cypari2.stack cimport new_gen 

  

from sage.libs.mpmath.utils cimport mpfr_to_mpfval 

  

from .integer cimport Integer 

from .rational cimport Rational 

  

from sage.categories.map cimport Map 

  

cdef ZZ, QQ, RDF 

from .integer_ring import ZZ 

from .rational_field import QQ 

from .real_double import RDF 

from .real_double cimport RealDoubleElement 

  

import sage.rings.rational_field 

  

import sage.rings.infinity 

  

from sage.structure.parent_gens cimport ParentWithGens 

from sage.arith.numerical_approx cimport digits_to_bits 

  

IF HAVE_GMPY2: 

cimport gmpy2 

gmpy2.import_gmpy2() 

  

  

#***************************************************************************** 

# 

# Implementation 

# 

#***************************************************************************** 

  

_re_skip_zeroes = re.compile(r'^(.+?)0*$') 

  

cdef object numpy_double_interface = {'typestr': '=f8'} 

cdef object numpy_object_interface = {'typestr': '|O'} 

  

# Avoid signal handling for cheap operations when the 

# precision is below this threshold. 

cdef enum: 

SIG_PREC_THRESHOLD = 1000 

  

#***************************************************************************** 

# 

# External Python access to constants 

# 

#***************************************************************************** 

  

def mpfr_prec_min(): 

""" 

Return the mpfr variable ``MPFR_PREC_MIN``. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_mpfr import mpfr_prec_min 

sage: mpfr_prec_min() 

1 

sage: R = RealField(2) 

sage: R(2) + R(1) 

3.0 

sage: R(4) + R(1) 

4.0 

sage: R = RealField(0) 

Traceback (most recent call last): 

... 

ValueError: prec (=0) must be >= 1 and <= 2147483391 

""" 

return MPFR_PREC_MIN 

  

# see Trac #11666 for the origin of this magical constant 

cdef int MY_MPFR_PREC_MAX = 2147483647 - 256 # = 2^31-257 

def mpfr_prec_max(): 

""" 

TESTS:: 

  

sage: from sage.rings.real_mpfr import mpfr_prec_max 

sage: mpfr_prec_max() 

2147483391 

sage: R = RealField(2^31-257) 

sage: R 

Real Field with 2147483391 bits of precision 

sage: R = RealField(2^31-256) 

Traceback (most recent call last): 

... 

ValueError: prec (=2147483392) must be >= 1 and <= 2147483391 

""" 

global MY_MPFR_PREC_MAX 

return MY_MPFR_PREC_MAX 

  

def mpfr_get_exp_min(): 

""" 

Return the current minimal exponent for MPFR numbers. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_mpfr import mpfr_get_exp_min 

sage: mpfr_get_exp_min() 

-1073741823 # 32-bit 

-4611686018427387903 # 64-bit 

sage: 0.5 >> (-mpfr_get_exp_min()) 

2.38256490488795e-323228497 # 32-bit 

8.50969131174084e-1388255822130839284 # 64-bit 

sage: 0.5 >> (-mpfr_get_exp_min()+1) 

0.000000000000000 

""" 

return mpfr_get_emin() 

  

def mpfr_get_exp_max(): 

""" 

Return the current maximal exponent for MPFR numbers. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_mpfr import mpfr_get_exp_max 

sage: mpfr_get_exp_max() 

1073741823 # 32-bit 

4611686018427387903 # 64-bit 

sage: 0.5 << mpfr_get_exp_max() 

1.04928935823369e323228496 # 32-bit 

2.93782689455579e1388255822130839282 # 64-bit 

sage: 0.5 << (mpfr_get_exp_max()+1) 

+infinity 

""" 

return mpfr_get_emax() 

  

def mpfr_set_exp_min(mp_exp_t e): 

""" 

Set the minimal exponent for MPFR numbers. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_mpfr import mpfr_get_exp_min, mpfr_set_exp_min 

sage: old = mpfr_get_exp_min() 

sage: mpfr_set_exp_min(-1000) 

sage: 0.5 >> 1000 

4.66631809251609e-302 

sage: 0.5 >> 1001 

0.000000000000000 

sage: mpfr_set_exp_min(old) 

sage: 0.5 >> 1001 

2.33315904625805e-302 

""" 

if mpfr_set_emin(e) != 0: 

raise OverflowError("bad value for mpfr_set_exp_min()") 

  

def mpfr_set_exp_max(mp_exp_t e): 

""" 

Set the maximal exponent for MPFR numbers. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_mpfr import mpfr_get_exp_max, mpfr_set_exp_max 

sage: old = mpfr_get_exp_max() 

sage: mpfr_set_exp_max(1000) 

sage: 0.5 << 1000 

5.35754303593134e300 

sage: 0.5 << 1001 

+infinity 

sage: mpfr_set_exp_max(old) 

sage: 0.5 << 1001 

1.07150860718627e301 

""" 

if mpfr_set_emax(e) != 0: 

raise OverflowError("bad value for mpfr_set_exp_max()") 

  

def mpfr_get_exp_min_min(): 

""" 

Get the minimal value allowed for :func:`mpfr_set_exp_min`. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_mpfr import mpfr_get_exp_min_min, mpfr_set_exp_min 

sage: mpfr_get_exp_min_min() 

-1073741823 # 32-bit 

-4611686018427387903 # 64-bit 

  

This is really the minimal value allowed:: 

  

sage: mpfr_set_exp_min(mpfr_get_exp_min_min() - 1) 

Traceback (most recent call last): 

... 

OverflowError: bad value for mpfr_set_exp_min() 

""" 

return mpfr_get_emin_min() 

  

def mpfr_get_exp_max_max(): 

""" 

Get the maximal value allowed for :func:`mpfr_set_exp_max`. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_mpfr import mpfr_get_exp_max_max, mpfr_set_exp_max 

sage: mpfr_get_exp_max_max() 

1073741823 # 32-bit 

4611686018427387903 # 64-bit 

  

This is really the maximal value allowed:: 

  

sage: mpfr_set_exp_max(mpfr_get_exp_max_max() + 1) 

Traceback (most recent call last): 

... 

OverflowError: bad value for mpfr_set_exp_max() 

""" 

return mpfr_get_emax_max() 

  

# On Sage startup, set the exponent range to the maximum allowed 

mpfr_set_exp_min(mpfr_get_emin_min()) 

mpfr_set_exp_max(mpfr_get_emax_max()) 

  

#***************************************************************************** 

# 

# Real Field 

# 

#***************************************************************************** 

# The real field is in Cython, so mpfr elements will have access to 

# their parent via direct C calls, which will be faster. 

  

from sage.arith.long cimport (pyobject_to_long, integer_check_long_py, 

ERR_OVERFLOW) 

cdef dict rounding_modes = dict(RNDN=MPFR_RNDN, RNDZ=MPFR_RNDZ, 

RNDD=MPFR_RNDD, RNDU=MPFR_RNDU, RNDA=MPFR_RNDA, RNDF=MPFR_RNDF) 

  

cdef double LOG_TEN_TWO_PLUS_EPSILON = 3.321928094887363 # a small overestimate of log(10,2) 

  

cdef object RealField_cache = sage.misc.weak_dict.WeakValueDictionary() 

  

cpdef RealField(int prec=53, int sci_not=0, rnd=MPFR_RNDN): 

""" 

RealField(prec, sci_not, rnd): 

  

INPUT: 

  

- ``prec`` -- (integer) precision; default = 53 prec is 

the number of bits used to represent the mantissa of a 

floating-point number. The precision can be any integer between 

:func:`mpfr_prec_min()` and :func:`mpfr_prec_max()`. In the current 

implementation, :func:`mpfr_prec_min()` is equal to 2. 

  

- ``sci_not`` -- (default: ``False``) if ``True``, always display using 

scientific notation; if ``False``, display using scientific notation 

only for very large or very small numbers 

  

- ``rnd`` -- (string) the rounding mode: 

  

- ``'RNDN'`` -- (default) round to nearest (ties go to the even 

number): Knuth says this is the best choice to prevent "floating 

point drift" 

- ``'RNDD'`` -- round towards minus infinity 

- ``'RNDZ'`` -- round towards zero 

- ``'RNDU'`` -- round towards plus infinity 

- ``'RNDA'`` -- round away from zero 

- ``'RNDF'`` -- faithful rounding (currently experimental; not 

guaranteed correct for every operation) 

- for specialized applications, the rounding mode can also be 

given as an integer value of type ``mpfr_rnd_t``. However, the 

exact values are unspecified. 

  

EXAMPLES:: 

  

sage: RealField(10) 

Real Field with 10 bits of precision 

sage: RealField() 

Real Field with 53 bits of precision 

sage: RealField(100000) 

Real Field with 100000 bits of precision 

  

Here we show the effect of rounding:: 

  

sage: R17d = RealField(17,rnd='RNDD') 

sage: a = R17d(1)/R17d(3); a.exact_rational() 

87381/262144 

sage: R17u = RealField(17,rnd='RNDU') 

sage: a = R17u(1)/R17u(3); a.exact_rational() 

43691/131072 

  

.. NOTE:: 

  

The default precision is 53, since according to the MPFR 

manual: 'mpfr should be able to exactly reproduce all 

computations with double-precision machine floating-point 

numbers (double type in C), except the default exponent range 

is much wider and subnormal numbers are not implemented.' 

""" 

# We allow specifying the rounding mode as string or integer. 

# But we pass an integer to __init__ 

cdef long r 

try: 

r = pyobject_to_long(rnd) 

except TypeError: 

try: 

r = rounding_modes[rnd] 

except KeyError: 

raise ValueError("rounding mode (={!r}) must be one of {}".format(rnd, rounding_modes.keys())) 

  

try: 

return RealField_cache[prec, sci_not, r] 

except KeyError: 

R = RealField_class(prec=prec, sci_not=sci_not, rnd=r) 

RealField_cache[prec, sci_not, r] = R 

return R 

  

  

cdef class RealField_class(sage.rings.ring.Field): 

""" 

An approximation to the field of real numbers using floating point 

numbers with any specified precision. Answers derived from 

calculations in this approximation may differ from what they would 

be if those calculations were performed in the true field of real 

numbers. This is due to the rounding errors inherent to finite 

precision calculations. 

  

See the documentation for the module :mod:`sage.rings.real_mpfr` for more 

details. 

""" 

def __init__(self, int prec=53, int sci_not=0, long rnd=MPFR_RNDN): 

""" 

Initialize ``self``. 

  

EXAMPLES:: 

  

sage: RealField() 

Real Field with 53 bits of precision 

sage: RealField(100000) 

Real Field with 100000 bits of precision 

sage: RealField(17,rnd='RNDD') 

Real Field with 17 bits of precision and rounding RNDD 

  

TESTS: 

  

Test the various rounding modes:: 

  

sage: RealField(100, rnd="RNDN") 

Real Field with 100 bits of precision 

sage: RealField(100, rnd="RNDZ") 

Real Field with 100 bits of precision and rounding RNDZ 

sage: RealField(100, rnd="RNDU") 

Real Field with 100 bits of precision and rounding RNDU 

sage: RealField(100, rnd="RNDD") 

Real Field with 100 bits of precision and rounding RNDD 

sage: RealField(100, rnd="RNDA") 

Real Field with 100 bits of precision and rounding RNDA 

sage: RealField(100, rnd="RNDF") 

Real Field with 100 bits of precision and rounding RNDF 

sage: RealField(100, rnd=0) 

Real Field with 100 bits of precision 

sage: RealField(100, rnd=1) 

Real Field with 100 bits of precision and rounding RNDZ 

sage: RealField(100, rnd=2) 

Real Field with 100 bits of precision and rounding RNDU 

sage: RealField(100, rnd=3) 

Real Field with 100 bits of precision and rounding RNDD 

sage: RealField(100, rnd=4) 

Real Field with 100 bits of precision and rounding RNDA 

sage: RealField(100, rnd=5) 

Real Field with 100 bits of precision and rounding RNDF 

sage: RealField(100, rnd=3.14) 

Traceback (most recent call last): 

... 

ValueError: rounding mode (=3.14000000000000) must be one of ['RNDA', 'RNDD', 'RNDF', 'RNDN', 'RNDU', 'RNDZ'] 

sage: RealField(100, rnd=6) 

Traceback (most recent call last): 

... 

ValueError: unknown rounding mode 6 

sage: RealField(100, rnd=10^100) 

Traceback (most recent call last): 

... 

OverflowError: Sage Integer too large to convert to C long 

""" 

global MY_MPFR_PREC_MAX 

if prec < MPFR_PREC_MIN or prec > MY_MPFR_PREC_MAX: 

raise ValueError("prec (=%s) must be >= %s and <= %s" % ( 

prec, MPFR_PREC_MIN, MY_MPFR_PREC_MAX)) 

self.__prec = prec 

self.sci_not = sci_not 

  

self.rnd = <mpfr_rnd_t>rnd 

cdef const char* rnd_str = mpfr_print_rnd_mode(self.rnd) 

if rnd_str is NULL: 

raise ValueError("unknown rounding mode {}".format(rnd)) 

self.rnd_str = char_to_str(rnd_str + 5) # Strip "MPFR_" 

  

from sage.categories.fields import Fields 

ParentWithGens.__init__(self, self, tuple([]), False, category=Fields().Metric().Complete()) 

  

# Initialize zero and one 

cdef RealNumber rn 

rn = self._new() 

mpfr_set_zero(rn.value, 1) 

self._zero_element = rn 

  

rn = self._new() 

mpfr_set_ui(rn.value, 1, MPFR_RNDZ) 

self._one_element = rn 

  

self._populate_coercion_lists_(convert_method_name='_mpfr_') 

  

def _repr_(self): 

""" 

Return a string representation of ``self``. 

  

EXAMPLES:: 

  

sage: RealField() # indirect doctest 

Real Field with 53 bits of precision 

sage: RealField(100000) # indirect doctest 

Real Field with 100000 bits of precision 

sage: RealField(17,rnd='RNDD') # indirect doctest 

Real Field with 17 bits of precision and rounding RNDD 

""" 

s = "Real Field with %s bits of precision"%self.__prec 

if self.rnd != MPFR_RNDN: 

s = s + " and rounding %s"%(self.rnd_str) 

return s 

  

def _latex_(self): 

r""" 

Return a latex representation of ``self``. 

  

EXAMPLES:: 

  

sage: latex(RealField()) # indirect doctest 

\Bold{R} 

""" 

return "\\Bold{R}" 

  

def _sage_input_(self, sib, coerce): 

r""" 

Produce an expression which will reproduce this value when 

evaluated. 

  

EXAMPLES:: 

  

sage: sage_input(RR, verify=True) 

# Verified 

RR 

sage: sage_input(RealField(25, rnd='RNDZ'), verify=True) 

# Verified 

RealField(25, rnd='RNDZ') 

sage: k = (RR, RealField(75, rnd='RNDU'), RealField(13)) 

sage: sage_input(k, verify=True) 

# Verified 

(RR, RealField(75, rnd='RNDU'), RealField(13)) 

sage: sage_input((k, k), verify=True) 

# Verified 

RR75u = RealField(75, rnd='RNDU') 

RR13 = RealField(13) 

((RR, RR75u, RR13), (RR, RR75u, RR13)) 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: RealField(99, rnd='RNDD')._sage_input_(SageInputBuilder(), False) 

{call: {atomic:RealField}({atomic:99}, rnd={atomic:'RNDD'})} 

""" 

if self.rnd == MPFR_RNDN and self.prec() == 53: 

return sib.name('RR') 

  

if self.rnd != MPFR_RNDN: 

rnd_abbrev = self.rnd_str[-1:].lower() 

v = sib.name('RealField')(sib.int(self.prec()), rnd=self.rnd_str) 

else: 

rnd_abbrev = '' 

v = sib.name('RealField')(sib.int(self.prec())) 

  

name = 'RR%d%s' % (self.prec(), rnd_abbrev) 

sib.cache(self, v, name) 

return v 

  

cpdef bint is_exact(self) except -2: 

""" 

Return ``False``, since a real field (represented using finite 

precision) is not exact. 

  

EXAMPLES:: 

  

sage: RR.is_exact() 

False 

sage: RealField(100).is_exact() 

False 

""" 

return False 

  

def _element_constructor_(self, x, base=10): 

""" 

Coerce ``x`` into this real field. 

  

EXAMPLES:: 

  

sage: R = RealField(20) 

sage: R('1.234') 

1.2340 

sage: R('2', base=2) 

Traceback (most recent call last): 

... 

TypeError: unable to convert '2' to a real number 

sage: a = R('1.1001', base=2); a 

1.5625 

sage: a.str(2) 

'1.1001000000000000000' 

sage: R(oo) 

+infinity 

sage: R(unsigned_infinity) 

Traceback (most recent call last): 

... 

ValueError: can only convert signed infinity to RR 

sage: R(CIF(NaN)) 

NaN 

sage: R(complex(1.7)) 

1.7000 

""" 

if hasattr(x, '_mpfr_'): 

return x._mpfr_(self) 

cdef RealNumber z 

z = self._new() 

z._set(x, base) 

return z 

  

cpdef _coerce_map_from_(self, S): 

""" 

Canonical coercion of x to this MPFR real field. 

  

The rings that canonically coerce to this MPFR real field are: 

  

- Any MPFR real field with precision that is as large as this one 

  

- int, long, integer, and rational rings. 

  

- the field of algebraic reals 

  

- floats and RDF if self.prec = 53 

  

EXAMPLES:: 

  

sage: RR.has_coerce_map_from(ZZ) # indirect doctest 

True 

sage: RR.has_coerce_map_from(float) 

True 

sage: RealField(100).has_coerce_map_from(float) 

False 

sage: RR.has_coerce_map_from(RealField(200)) 

True 

sage: RR.has_coerce_map_from(RealField(20)) 

False 

sage: RR.has_coerce_map_from(RDF) 

True 

sage: RR.coerce_map_from(ZZ)(2) 

2.00000000000000 

sage: RR.coerce(3.4r) 

3.40000000000000 

sage: RR.coerce(3.4) 

3.40000000000000 

sage: RR.coerce(3.4r) 

3.40000000000000 

sage: RR.coerce(3.400000000000000000000000000000000000000000) 

3.40000000000000 

sage: RealField(100).coerce(3.4) 

Traceback (most recent call last): 

... 

TypeError: no canonical coercion from Real Field with 53 bits of precision to Real Field with 100 bits of precision 

sage: RR.coerce(17/5) 

3.40000000000000 

sage: RR.coerce(2^4000) 

1.31820409343094e1204 

sage: RR.coerce_map_from(float) 

Generic map: 

From: Set of Python objects of class 'float' 

To: Real Field with 53 bits of precision 

  

TESTS:: 

  

sage: 1.0 - ZZ(1) - int(1) - long(1) - QQ(1) - RealField(100)(1) - AA(1) - RLF(1) 

-6.00000000000000 

sage: R = RR['x'] # Hold reference to avoid garbage collection, see Trac #24709 

sage: R.get_action(ZZ) 

Right scalar multiplication by Integer Ring on Univariate Polynomial Ring in x over Real Field with 53 bits of precision 

""" 

if S is ZZ: 

return ZZtoRR(ZZ, self) 

elif S is QQ: 

return QQtoRR(QQ, self) 

elif (S is RDF or S is float) and self.__prec <= 53: 

return double_toRR(S, self) 

elif S is long: 

return int_toRR(long, self) 

elif S is int: 

return int_toRR(int, self) 

elif isinstance(S, RealField_class) and S.prec() >= self.__prec: 

return RRtoRR(S, self) 

elif QQ.has_coerce_map_from(S): 

return QQtoRR(QQ, self) * QQ._internal_coerce_map_from(S) 

from sage.rings.qqbar import AA 

from sage.rings.real_lazy import RLF 

if S is AA or S is RLF: 

return self.convert_method_map(S, "_mpfr_") 

return self._coerce_map_via([RLF], S) 

  

def __richcmp__(RealField_class self, other, int op): 

""" 

Compare two real fields, returning ``True`` if they are equivalent 

and ``False`` if they are not. 

  

EXAMPLES:: 

  

sage: RealField(10) == RealField(11) 

False 

sage: RealField(10) == RealField(10) 

True 

sage: RealField(10,rnd='RNDN') == RealField(10,rnd='RNDZ') 

False 

  

Scientific notation affects only printing, not mathematically how 

the field works, so this does not affect equality testing:: 

  

sage: RealField(10,sci_not=True) == RealField(10,sci_not=False) 

True 

sage: RealField(10) == IntegerRing() 

False 

  

:: 

  

sage: RS = RealField(sci_not=True) 

sage: RR == RS 

True 

sage: RS.scientific_notation(False) 

sage: RR == RS 

True 

""" 

if op != Py_EQ and op != Py_NE: 

return NotImplemented 

if not isinstance(other, RealField_class): 

return NotImplemented 

  

_other = <RealField_class>other # to access C structure 

return (self.__prec == _other.__prec and 

self.rnd == _other.rnd) == (op == Py_EQ) 

  

def __reduce__(self): 

""" 

Return the arguments sufficient for pickling. 

  

EXAMPLES:: 

  

sage: R = RealField(sci_not=1, prec=200, rnd='RNDU') 

sage: loads(dumps(R)) == R 

True 

""" 

return __create__RealField_version0, (self.__prec, self.sci_not, self.rnd_str) 

  

def construction(self): 

r""" 

Return the functorial construction of ``self``, namely, 

completion of the rational numbers with respect to the prime 

at `\infty`. 

  

Also preserves other information that makes this field unique (e.g. 

precision, rounding, print mode). 

  

EXAMPLES:: 

  

sage: R = RealField(100, rnd='RNDU') 

sage: c, S = R.construction(); S 

Rational Field 

sage: R == c(S) 

True 

""" 

from sage.categories.pushout import CompletionFunctor 

return (CompletionFunctor(sage.rings.infinity.Infinity, 

self.prec(), 

{'type': 'MPFR', 'sci_not': self.scientific_notation(), 'rnd': self.rnd}), 

sage.rings.rational_field.QQ) 

  

def gen(self, i=0): 

""" 

Return the ``i``-th generator of ``self``. 

  

EXAMPLES:: 

  

sage: R=RealField(100) 

sage: R.gen(0) 

1.0000000000000000000000000000 

sage: R.gen(1) 

Traceback (most recent call last): 

... 

IndexError: self has only one generator 

""" 

if i == 0: 

return self(1) 

else: 

raise IndexError("self has only one generator") 

  

def complex_field(self): 

""" 

Return complex field of the same precision. 

  

EXAMPLES:: 

  

sage: RR.complex_field() 

Complex Field with 53 bits of precision 

sage: RR.complex_field() is CC 

True 

sage: RealField(100,rnd='RNDD').complex_field() 

Complex Field with 100 bits of precision 

sage: RealField(100).complex_field() 

Complex Field with 100 bits of precision 

""" 

from sage.rings.complex_field import ComplexField 

return ComplexField(self.prec()) 

  

def algebraic_closure(self): 

""" 

Return the algebraic closure of ``self``, i.e., the complex field with 

the same precision. 

  

EXAMPLES:: 

  

sage: RR.algebraic_closure() 

Complex Field with 53 bits of precision 

sage: RR.algebraic_closure() is CC 

True 

sage: RealField(100,rnd='RNDD').algebraic_closure() 

Complex Field with 100 bits of precision 

sage: RealField(100).algebraic_closure() 

Complex Field with 100 bits of precision 

""" 

return self.complex_field() 

  

def ngens(self): 

""" 

Return the number of generators. 

  

EXAMPLES:: 

  

sage: RR.ngens() 

1 

""" 

return 1 

  

def gens(self): 

""" 

Return a list of generators. 

  

EXAMPLES:: 

  

sage: RR.gens() 

[1.00000000000000] 

""" 

return [self.gen()] 

  

def _is_valid_homomorphism_(self, codomain, im_gens): 

""" 

Return ``True`` if the map from ``self`` to ``codomain`` sending 

``self(1)`` to the unique element of ``im_gens`` is a valid field 

homomorphism. Otherwise, return ``False``. 

  

EXAMPLES:: 

  

sage: RR._is_valid_homomorphism_(RDF,[RDF(1)]) 

True 

sage: RR._is_valid_homomorphism_(CDF,[CDF(1)]) 

True 

sage: RR._is_valid_homomorphism_(CDF,[CDF(-1)]) 

False 

sage: R=RealField(100) 

sage: RR._is_valid_homomorphism_(R,[R(1)]) 

False 

sage: RR._is_valid_homomorphism_(CC,[CC(1)]) 

True 

sage: RR._is_valid_homomorphism_(GF(2),GF(2)(1)) 

False 

""" 

  

try: 

s = codomain.coerce(self(1)) 

except TypeError: 

return False 

return s == im_gens[0] 

  

def _repr_option(self, key): 

""" 

Metadata about the :meth:`_repr_` output. 

  

See :meth:`sage.structure.parent._repr_option` for details. 

  

EXAMPLES:: 

  

sage: RealField(10)._repr_option('element_is_atomic') 

True 

""" 

if key == 'element_is_atomic': 

return True 

return super(RealField_class, self)._repr_option(key) 

  

def is_finite(self): 

""" 

Return ``False``, since the field of real numbers is not finite. 

  

EXAMPLES:: 

  

sage: RealField(10).is_finite() 

False 

""" 

return False 

  

def characteristic(self): 

""" 

Returns 0, since the field of real numbers has characteristic 0. 

  

EXAMPLES:: 

  

sage: RealField(10).characteristic() 

0 

""" 

return Integer(0) 

  

def name(self): 

""" 

Return the name of ``self``, which encodes the precision and 

rounding convention. 

  

EXAMPLES:: 

  

sage: RR.name() 

'RealField53_0' 

sage: RealField(100,rnd='RNDU').name() 

'RealField100_2' 

""" 

return "RealField%s_%s"%(self.__prec,self.rnd) 

  

def __hash__(self): 

""" 

Returns a hash function of the field, which takes into account 

the precision and rounding convention. 

  

EXAMPLES:: 

  

sage: hash(RealField(100,rnd='RNDU')) == hash(RealField(100,rnd='RNDU')) 

True 

sage: hash(RR) == hash(RealField(53)) 

True 

""" 

return hash(self.name()) 

  

def precision(self): 

""" 

Return the precision of ``self``. 

  

EXAMPLES:: 

  

sage: RR.precision() 

53 

sage: RealField(20).precision() 

20 

""" 

return self.__prec 

  

prec=precision # an alias 

  

def _magma_init_(self, magma): 

r""" 

Return a string representation of ``self`` in the Magma language. 

  

.. WARNING:: 

  

This ignores the rounding convention of ``self``. 

  

EXAMPLES:: 

  

sage: magma(RealField(70)) # optional - magma # indirect doctest 

Real field of precision 21 

sage: 10^21 < 2^70 < 10^22 

True 

sage: s = magma(RealField(70)).sage(); s # optional - magma # indirect doctest 

Real Field with 70 bits of precision 

""" 

return "RealField(%s : Bits := true)" % self.prec() 

  

def to_prec(self, prec): 

""" 

Return the real field that is identical to ``self``, except that 

it has the specified precision. 

  

EXAMPLES:: 

  

sage: RR.to_prec(212) 

Real Field with 212 bits of precision 

sage: R = RealField(30, rnd="RNDZ") 

sage: R.to_prec(300) 

Real Field with 300 bits of precision and rounding RNDZ 

""" 

if prec == self.__prec: 

return self 

else: 

return RealField(prec, self.sci_not, self.rnd) 

  

def pi(self): 

r""" 

Return `\pi` to the precision of this field. 

  

EXAMPLES:: 

  

sage: R = RealField(100) 

sage: R.pi() 

3.1415926535897932384626433833 

sage: R.pi().sqrt()/2 

0.88622692545275801364908374167 

sage: R = RealField(150) 

sage: R.pi().sqrt()/2 

0.88622692545275801364908374167057259139877473 

""" 

cdef RealNumber x = self._new() 

if self.__prec > SIG_PREC_THRESHOLD: sig_on() 

# The docs for mpfr_free_cache say "Free the cache used by 

# the functions computing constants if needed (currently 

# mpfr_const_log2, mpfr_const_pi and mpfr_const_euler)", so 

# this isn't a seriously bad thing to do. This prevents trac 

# #5689. This is needed for all constants, despite what the docs say. 

# NOTE: The MPFR docs at this time leave off several mpfr_const 

# functions, but this free is needed for them too! 

mpfr_free_cache() 

mpfr_const_pi(x.value, self.rnd) 

if self.__prec > SIG_PREC_THRESHOLD: sig_off() 

return x 

  

def euler_constant(self): 

""" 

Returns Euler's gamma constant to the precision of this field. 

  

EXAMPLES:: 

  

sage: RealField(100).euler_constant() 

0.57721566490153286060651209008 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_free_cache() 

mpfr_const_euler(x.value, self.rnd) 

sig_off() 

return x 

  

def catalan_constant(self): 

""" 

Returns Catalan's constant to the precision of this field. 

  

EXAMPLES:: 

  

sage: RealField(100).catalan_constant() 

0.91596559417721901505460351493 

""" 

cdef RealNumber x = self._new() 

if self.__prec > SIG_PREC_THRESHOLD: sig_on() 

mpfr_free_cache() 

mpfr_const_catalan(x.value, self.rnd) 

if self.__prec > SIG_PREC_THRESHOLD: sig_off() 

return x 

  

def log2(self): 

r""" 

Return `\log(2)` (i.e., the natural log of 2) to the precision 

of this field. 

  

EXAMPLES:: 

  

sage: R=RealField(100) 

sage: R.log2() 

0.69314718055994530941723212146 

sage: R(2).log() 

0.69314718055994530941723212146 

""" 

cdef RealNumber x = self._new() 

if self.__prec > SIG_PREC_THRESHOLD: sig_on() 

mpfr_free_cache() 

mpfr_const_log2(x.value, self.rnd) 

if self.__prec > SIG_PREC_THRESHOLD: sig_off() 

return x 

  

def random_element(self, min=-1, max=1, distribution=None): 

""" 

Return a uniformly distributed random number between ``min`` and 

``max`` (default -1 to 1). 

  

.. WARNING:: 

  

The argument ``distribution`` is ignored---the random number 

is from the uniform distribution. 

  

EXAMPLES:: 

  

sage: RealField(100).random_element(-5, 10) 

-1.7093633198207765227646362966 

sage: RealField(10).random_element() 

-0.11 

  

TESTS:: 

  

sage: RealField(31).random_element() 

-0.676162510 

sage: RealField(32).random_element() 

0.689774422 

sage: RealField(33).random_element() 

0.396496861 

sage: RealField(63).random_element() 

-0.339980711116375371 

sage: RealField(64).random_element() 

-0.0453049884016705260 

sage: RealField(65).random_element() 

-0.5926714709589708137 

sage: RealField(10).random_element() 

0.23 

sage: RealField(10).random_element() 

-0.41 

sage: RR.random_element() 

-0.0420335212948924 

sage: RR.random_element() 

-0.616678906367394 

""" 

cdef RealNumber x = self._new() 

cdef randstate rstate = current_randstate() 

mpfr_urandomb(x.value, rstate.gmp_state) 

if min == 0 and max == 1: 

return x 

else: 

return (max-min)*x + min 

  

def factorial(self, int n): 

""" 

Return the factorial of the integer ``n`` as a real number. 

  

EXAMPLES:: 

  

sage: RR.factorial(0) 

1.00000000000000 

sage: RR.factorial(1000000) 

8.26393168833124e5565708 

sage: RR.factorial(-1) 

Traceback (most recent call last): 

... 

ArithmeticError: n must be nonnegative 

""" 

cdef RealNumber x 

if n < 0: 

raise ArithmeticError("n must be nonnegative") 

x = self._new() 

if self.__prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_on() 

mpfr_fac_ui(x.value, n, self.rnd) 

if self.__prec > SIG_PREC_THRESHOLD and n < SIG_PREC_THRESHOLD: sig_off() 

return x 

  

def rounding_mode(self): 

""" 

Return the rounding mode. 

  

EXAMPLES:: 

  

sage: RR.rounding_mode() 

'RNDN' 

sage: RealField(20,rnd='RNDZ').rounding_mode() 

'RNDZ' 

sage: RealField(20,rnd='RNDU').rounding_mode() 

'RNDU' 

sage: RealField(20,rnd='RNDD').rounding_mode() 

'RNDD' 

""" 

return self.rnd_str 

  

def scientific_notation(self, status=None): 

""" 

Set or return the scientific notation printing flag. If this flag 

is ``True`` then real numbers with this space as parent print using 

scientific notation. 

  

INPUT: 

  

- ``status`` -- boolean optional flag 

  

EXAMPLES:: 

  

sage: RR.scientific_notation() 

False 

sage: elt = RR(0.2512); elt 

0.251200000000000 

sage: RR.scientific_notation(True) 

sage: elt 

2.51200000000000e-1 

sage: RR.scientific_notation() 

True 

sage: RR.scientific_notation(False) 

sage: elt 

0.251200000000000 

sage: R = RealField(20, sci_not=1) 

sage: R.scientific_notation() 

True 

sage: R(0.2512) 

2.5120e-1 

""" 

if status is None: 

return self.sci_not 

else: 

self.sci_not = status 

  

def zeta(self, n=2): 

""" 

Return an `n`-th root of unity in the real field, if one 

exists, or raise a ``ValueError`` otherwise. 

  

EXAMPLES:: 

  

sage: R = RealField() 

sage: R.zeta() 

-1.00000000000000 

sage: R.zeta(1) 

1.00000000000000 

sage: R.zeta(5) 

Traceback (most recent call last): 

... 

ValueError: No 5th root of unity in self 

""" 

if n == 1: 

return self(1) 

elif n == 2: 

return self(-1) 

raise ValueError("No %sth root of unity in self" % n) 

  

def _factor_univariate_polynomial(self, f): 

""" 

Factor the univariate polynomial ``f``. 

  

INPUT: 

  

- ``f`` -- a univariate polynomial defined over the real numbers 

  

OUTPUT: 

  

- A factorization of ``f`` over the real numbers into a unit and monic 

irreducible factors 

  

.. NOTE:: 

  

This is a helper method for 

:meth:`sage.rings.polynomial.polynomial_element.Polynomial.factor`. 

  

This method calls PARI to compute the factorization. 

  

TESTS:: 

  

sage: k = RealField(100) 

sage: R.<x> = k[] 

sage: k._factor_univariate_polynomial( x ) 

x 

sage: k._factor_univariate_polynomial( 2*x ) 

(2.0000000000000000000000000000) * x 

sage: k._factor_univariate_polynomial( x^2 ) 

x^2 

sage: k._factor_univariate_polynomial( x^2 + 1 ) 

x^2 + 1.0000000000000000000000000000 

sage: k._factor_univariate_polynomial( x^2 - 1 ) 

(x - 1.0000000000000000000000000000) * (x + 1.0000000000000000000000000000) 

sage: k._factor_univariate_polynomial( (x - 1)^3 ) 

(x - 1.0000000000000000000000000000)^3 

sage: k._factor_univariate_polynomial( x^2 - 3 ) 

(x - 1.7320508075688772935274463415) * (x + 1.7320508075688772935274463415) 

  

""" 

R = f.parent() 

F = list(f._pari_with_name().factor()) 

  

from sage.structure.factorization import Factorization 

return Factorization([(R(g).monic(),e) for g,e in zip(*F)], f.leading_coefficient()) 

  

#***************************************************************************** 

# 

# RealNumber -- element of Real Field 

# 

#***************************************************************************** 

  

cdef class RealLiteral(RealNumber) 

  

cdef class RealNumber(sage.structure.element.RingElement): 

""" 

A floating point approximation to a real number using any specified 

precision. Answers derived from calculations with such 

approximations may differ from what they would be if those 

calculations were performed with true real numbers. This is due to 

the rounding errors inherent to finite precision calculations. 

  

The approximation is printed to slightly fewer digits than its 

internal precision, in order to avoid confusing roundoff issues 

that occur because numbers are stored internally in binary. 

""" 

def __cinit__(self, parent, x=None, base=None): 

""" 

Initialize the parent of this element and allocate memory 

  

TESTS:: 

  

sage: from sage.rings.real_mpfr import RealNumber 

sage: RealNumber.__new__(RealNumber, None) 

Traceback (most recent call last): 

... 

TypeError: Cannot convert NoneType to sage.rings.real_mpfr.RealField_class 

sage: RealNumber.__new__(RealNumber, ZZ) 

Traceback (most recent call last): 

... 

TypeError: Cannot convert sage.rings.integer_ring.IntegerRing_class to sage.rings.real_mpfr.RealField_class 

sage: RealNumber.__new__(RealNumber, RR) 

NaN 

""" 

cdef RealField_class p = <RealField_class?>parent 

mpfr_init2(self.value, p.__prec) 

self._parent = p 

  

def __init__(self, parent, x=0, int base=10): 

""" 

Create a real number. Should be called by first creating a 

RealField, as illustrated in the examples. 

  

EXAMPLES:: 

  

sage: R = RealField() 

sage: R('1.2456') 

1.24560000000000 

sage: R = RealField(3) 

sage: R('1.2456') 

1.2 

  

EXAMPLES: Rounding Modes 

  

:: 

  

sage: w = RealField(3)(5/2) 

sage: RealField(2, rnd="RNDZ")(w).str(2) 

'10.' 

sage: RealField(2, rnd="RNDD")(w).str(2) 

'10.' 

sage: RealField(2, rnd="RNDU")(w).str(2) 

'11.' 

sage: RealField(2, rnd="RNDN")(w).str(2) 

'10.' 

  

Conversion from gmpy2 numbers:: 

  

sage: from gmpy2 import * # optional - gmpy2 

sage: RR(mpz(5)) # optional - gmpy2 

5.00000000000000 

sage: RR(mpq(1/2)) # optional - gmpy2 

0.500000000000000 

sage: RR(mpfr('42.1')) # optional - gmpy2 

42.1000000000000 

  

.. NOTE:: 

  

A real number is an arbitrary precision mantissa with a 

limited precision exponent. A real number can have three 

special values: Not-a-Number (NaN) or plus or minus 

Infinity. NaN represents an uninitialized object, the 

result of an invalid operation (like 0 divided by 0), or a 

value that cannot be determined (like +Infinity minus 

+Infinity). Moreover, like in the IEEE 754-1985 standard, 

zero is signed, i.e. there are both +0 and -0; the behavior 

is the same as in the IEEE 754-1985 standard and it is 

generalized to the other functions supported by MPFR. 

  

TESTS:: 

  

sage: TestSuite(R).run() 

""" 

if x is not None: 

self._set(x, base) 

  

def _magma_init_(self, magma): 

r""" 

Return a string representation of ``self`` in the Magma language. 

  

EXAMPLES:: 

  

sage: magma(RR(10.5)) # indirect doctest, optional - magma 

10.5000000000000 

sage: magma(RealField(200)(1/3)) # indirect, optional - magma 

0.333333333333333333333333333333333333333333333333333333333333 

sage: magma(RealField(1000)(1/3)) # indirect, optional - magma 

0.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333 

""" 

real_string = self.str() 

digit_precision_upper_bound = len(real_string) 

return "%s!%sp%s" % (self.parent()._magma_init_(magma), 

real_string, digit_precision_upper_bound) 

  

@property 

def __array_interface__(self): 

""" 

Used for NumPy conversion. 

  

EXAMPLES:: 

  

sage: import numpy 

sage: numpy.arange(10.0) 

array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]) 

sage: numpy.array([1.0, 1.1, 1.2]).dtype 

dtype('float64') 

sage: numpy.array([1.000000000000000000000000000000000000]).dtype 

dtype('O') 

""" 

if (<RealField_class>self._parent).__prec <= 53: 

return numpy_double_interface 

else: 

return numpy_object_interface 

  

cdef _set(self, x, int base): 

# This should not be called except when the number is being created. 

# Real Numbers are supposed to be immutable. 

cdef RealField_class parent 

cdef Gen _gen 

parent = self._parent 

if isinstance(x, RealNumber): 

if isinstance(x, RealLiteral): 

s = (<RealLiteral>x).literal 

base = (<RealLiteral>x).base 

if mpfr_set_str(self.value, str_to_bytes(s), base, parent.rnd): 

self._set(s, base) 

else: 

mpfr_set(self.value, (<RealNumber>x).value, parent.rnd) 

elif isinstance(x, Integer): 

mpfr_set_z(self.value, (<Integer>x).value, parent.rnd) 

elif isinstance(x, Rational): 

mpfr_set_q(self.value, (<Rational>x).value, parent.rnd) 

elif isinstance(x, Gen) and typ((<Gen>x).g) == t_REAL: 

_gen = x 

self._set_from_GEN_REAL(_gen.g) 

elif isinstance(x, long): 

x = Integer(x) 

mpfr_set_z(self.value, (<Integer>x).value, parent.rnd) 

elif isinstance(x, int): 

mpfr_set_si(self.value, x, parent.rnd) 

elif isinstance(x, float): 

mpfr_set_d(self.value, x, parent.rnd) 

elif isinstance(x, complex) and x.imag == 0: 

mpfr_set_d(self.value, x.real, parent.rnd) 

elif isinstance(x, RealDoubleElement): 

mpfr_set_d(self.value, (<RealDoubleElement>x)._value, parent.rnd) 

elif HAVE_GMPY2 and type(x) is gmpy2.mpfr: 

mpfr_set(self.value, (<gmpy2.mpfr>x).f, parent.rnd) 

elif HAVE_GMPY2 and type(x) is gmpy2.mpq: 

mpfr_set_q(self.value, (<gmpy2.mpq>x).q, parent.rnd) 

elif HAVE_GMPY2 and type(x) is gmpy2.mpz: 

mpfr_set_z(self.value, (<gmpy2.mpz>x).z, parent.rnd) 

else: 

s = str(x).replace(' ','') 

s_lower = s.lower() 

if s_lower == 'infinity': 

raise ValueError('can only convert signed infinity to RR') 

elif mpfr_set_str(self.value, str_to_bytes(s), base, parent.rnd) == 0: 

pass 

elif s == 'NaN' or s == '@NaN@' or s == '[..NaN..]' or s == 'NaN+NaN*I': 

mpfr_set_nan(self.value) 

elif s_lower == '+infinity': 

mpfr_set_inf(self.value, 1) 

elif s_lower == '-infinity': 

mpfr_set_inf(self.value, -1) 

else: 

raise TypeError("unable to convert {!r} to a real number".format(s)) 

  

cdef _set_from_GEN_REAL(self, GEN g): 

""" 

EXAMPLES:: 

  

sage: rt2 = sqrt(pari('2.0')) 

sage: rt2 

1.41421356237310 

sage: rt2.sage() 

1.41421356237309505 

sage: rt2.sage().prec() 

64 

sage: pari(rt2.sage()) == rt2 

True 

sage: for i in range(100, 200): 

....: assert(sqrt(pari(i)) == pari(sqrt(pari(i)).sage())) 

sage: (-3.1415).__pari__().sage() 

-3.14150000000000000 

""" 

cdef int sgn 

sgn = signe(g) 

  

if sgn == 0: 

mpfr_set_ui(self.value, 0, MPFR_RNDN) 

return 

  

cdef int wordsize = 8 * sizeof(long) 

  

cdef mpz_t mantissa 

mpz_init(mantissa) 

mpz_import(mantissa, lg(g) - 2, 1, wordsize/8, 0, 0, &g[2]) 

  

cdef mp_exp_t exponent = expo(g) 

  

# Round to nearest for best results when setting a low-precision 

# MPFR from a high-precision GEN 

mpfr_set_z(self.value, mantissa, MPFR_RNDN) 

mpfr_mul_2si(self.value, self.value, exponent - wordsize * (lg(g) - 2) + 1, MPFR_RNDN) 

  

if sgn < 0: 

mpfr_neg(self.value, self.value, MPFR_RNDN) 

  

mpz_clear(mantissa) 

  

def __reduce__(self): 

""" 

EXAMPLES:: 

  

sage: R = RealField(sci_not=1, prec=200, rnd='RNDU') 

sage: b = R('393.39203845902384098234098230948209384028340') 

sage: loads(dumps(b)) == b 

True 

sage: b = R(1)/R(0); b 

+infinity 

sage: loads(dumps(b)) == b 

True 

sage: b = R(-1)/R(0); b 

-infinity 

sage: loads(dumps(b)) == b 

True 

sage: b = R(-1).sqrt(); b 

1.0000000000000000000000000000000000000000000000000000000000*I 

sage: loads(dumps(b)) == b 

True 

""" 

s = self.str(32, no_sci=False, e='@') 

return (__create__RealNumber_version0, (self._parent, s, 32)) 

  

def __dealloc__(self): 

if self._parent is not None: 

mpfr_clear(self.value) 

  

def __repr__(self): 

""" 

Return a string representation of ``self``. 

  

EXAMPLES:: 

  

sage: RR(2.1) # indirect doctest 

2.10000000000000 

""" 

return self.str(truncate=True) 

  

def _latex_(self): 

r""" 

Return a latex representation of ``self``. 

  

EXAMPLES:: 

  

sage: latex(RR(2.1)) # indirect doctest 

2.10000000000000 

sage: latex(RR(2e100)) # indirect doctest 

2.00000000000000 \times 10^{100} 

""" 

s = repr(self) 

parts = s.split('e') 

if len(parts) > 1: 

# scientific notation 

if parts[1][0] == '+': 

parts[1] = parts[1][1:] 

s = "%s \\times 10^{%s}" % (parts[0], parts[1]) 

return s 

  

def _interface_init_(self, I=None): 

""" 

Return string representation of ``self`` in base 10, avoiding 

scientific notation except for very large or very small numbers. 

  

This is most likely to make sense in other computer algebra systems 

(this function is the default for exporting to other computer 

algebra systems). 

  

EXAMPLES:: 

  

sage: n = 1.3939494594 

sage: n._interface_init_() 

'1.3939494593999999' 

sage: s1 = RR(sin(1)); s1 

0.841470984807897 

sage: s1._interface_init_() 

'0.84147098480789650' 

sage: s1 == RR(gp(s1)) 

True 

""" 

return self.str(10, no_sci=True) 

  

def _sage_input_(self, sib, coerced): 

r""" 

Produce an expression which will reproduce this value when evaluated. 

  

EXAMPLES:: 

  

sage: for prec in (2, 53, 200): 

....: for rnd_dir in ('RNDN', 'RNDD', 'RNDU', 'RNDZ'): 

....: fld = RealField(prec, rnd=rnd_dir) 

....: var = polygen(fld) 

....: for v in [NaN, -infinity, -20, -e, 0, 1, 2^500, -2^4000, -2^-500, 2^-4000] + [fld.random_element() for _ in range(5)]: 

....: for preparse in (True, False, None): 

....: _ = sage_input(fld(v), verify=True, preparse=preparse) 

....: _ = sage_input(fld(v) * var, verify=True, preparse=preparse) 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: sib_np = SageInputBuilder(preparse=False) 

sage: RR60 = RealField(60) 

sage: RR(-infinity)._sage_input_(sib, True) 

{unop:- {call: {atomic:RR}({atomic:Infinity})}} 

sage: RR(NaN)._sage_input_(sib, True) 

{call: {atomic:RR}({atomic:NaN})} 

sage: RR(12345)._sage_input_(sib, True) 

{atomic:12345} 

sage: RR(-12345)._sage_input_(sib, False) 

{unop:- {call: {atomic:RR}({atomic:12345})}} 

sage: RR(1.579)._sage_input_(sib, True) 

{atomic:1.579} 

sage: RR(1.579)._sage_input_(sib_np, True) 

{atomic:1.579} 

sage: RR60(1.579)._sage_input_(sib, True) 

{atomic:1.5790000000000000008} 

sage: RR60(1.579)._sage_input_(sib_np, True) 

{call: {call: {atomic:RealField}({atomic:60})}({atomic:'1.5790000000000000008'})} 

sage: RR(1.579)._sage_input_(sib_np, False) 

{call: {atomic:RR}({atomic:1.579})} 

sage: RR(1.579)._sage_input_(sib_np, 2) 

{atomic:1.579} 

sage: RealField(150)(pi)._sage_input_(sib, True) 

{atomic:3.1415926535897932384626433832795028841971694008} 

sage: RealField(150)(pi)._sage_input_(sib_np, True) 

{call: {call: {atomic:RealField}({atomic:150})}({atomic:'3.1415926535897932384626433832795028841971694008'})} 

""" 

# We have a bewildering array of conditions to deal with: 

# 1) number, or NaN or infinity 

# 2) rounding direction: up, down, or nearest 

# 3) preparser enabled: yes, no, or maybe 

# 4) is this number equal to some Python float: yes or no 

# 5) coerced 

  

# First, handle NaN and infinity 

if not mpfr_number_p(self.value): 

if mpfr_inf_p(self.value): 

v = sib.name('Infinity') 

else: 

v = sib.name('NaN') 

v = sib(self._parent)(v) 

if mpfr_sgn(self.value) < 0: 

v = -v 

return v 

  

from sage.rings.integer_ring import ZZ 

  

cdef mpfr_rnd_t rnd = (<RealField_class>self._parent).rnd 

  

cdef bint negative = mpfr_sgn(self.value) < 0 

if negative: 

self = -self 

  

# There are five possibilities for printing this floating-point 

# number, ordered from prettiest to ugliest (IMHO). 

# 1) An integer: 42 

# 2) A simple literal: 3.14159 

# 3) A coerced integer: RR(42) 

# 4) A coerced literal: RR(3.14159) 

# 5) A coerced string literal: RR('3.14159') 

  

# To use choice 1 or choice 3, this number must be an integer. 

cdef bint can_use_int_literal = \ 

self.abs() < (Integer(1) << self.prec()) and self in ZZ 

  

# If "not coerced", then we will introduce a conversion 

# ourselves. If coerced==2, then there will be an external conversion. 

# On the other hand, if coerced==1 (or True), then we only 

# have a coercion, not a conversion; which means we need to read 

# in a number with at least the number of bits we need. 

will_convert = (coerced == 2 or not coerced) 

  

self_str = self.str(skip_zeroes=(will_convert or self.prec() <= 53)) 

  

# To use choice 2 or choice 4, we must be able to read 

# numbers of this precision as a literal. We support this 

# only for the default rounding mode; "pretty" output for 

# other rounding modes is a lot of work for very little gain 

# (since other rounding modes are very rarely used). 

# (One problem is that we don't know whether it will be the 

# positive or negative value that will be coerced into the 

# desired parent; for example, this differs between "x^2 - 1.3*x" 

# and "-1.3*x".) 

cdef bint can_use_float_literal = \ 

rnd == MPFR_RNDN and (sib.preparse() or 

((will_convert or self.prec() <= 53) and 

self._parent(float(self_str)) == self)) 

  

if can_use_int_literal or can_use_float_literal: 

if can_use_int_literal: 

v = sib.int(self._integer_()) 

else: 

v = sib.float_str(self_str) 

if not coerced and (can_use_int_literal or not sib.preparse() or create_RealNumber(self_str).prec() != self.prec()): 

v = sib(self.parent())(v) 

else: 

if rnd == MPFR_RNDN: 

s = self_str 

else: 

# This is tricky. str() uses mpfr_get_str() with 

# digits=0; this guarantees to give enough digits 

# to recreate the input, if we print and read with 

# round-to-nearest. However, we are not going to 

# read with round-to-nearest, so we might need more digits. 

# If we're going to read with round-down, then we need 

# to print with round-up; and we'll use one more bit 

# to make sure we have enough digits. 

# Since we always read nonnegative numbers, reading with 

# RNDZ is the same as reading with RNDD. 

if rnd == MPFR_RNDD or rnd == MPFR_RNDZ: 

fld = RealField(self.prec() + 1, rnd='RNDU') 

else: 

fld = RealField(self.prec() + 1, rnd='RNDD') 

s = fld(self).str() 

v = sib(self.parent())(sib.float_str(repr(s))) 

  

if negative: 

v = -v 

  

return v 

  

def __hash__(self): 

""" 

Returns the hash of self, which coincides with the python float 

(and often int) type. 

  

This has the drawback that two very close high precision numbers 

will have the same hash, but allows them to play nicely with other 

real types. 

  

EXAMPLES:: 

  

sage: hash(RR(1.2)) == hash(1.2r) 

True 

""" 

return hash(float(self)) 

  

def _im_gens_(self, codomain, im_gens): 

""" 

Return the image of ``self`` under the homomorphism from the rational 

field to ``codomain``. 

  

This always just returns ``self`` coerced into the ``codomain``. 

  

EXAMPLES:: 

  

sage: RR(2.1)._im_gens_(RDF, [RDF(1)]) 

2.1 

sage: R = RealField(20) 

sage: RR(2.1)._im_gens_(R, [R(1)]) 

2.1000 

""" 

return codomain(self) # since 1 |--> 1 

  

def real(self): 

""" 

Return the real part of ``self``. 

  

(Since ``self`` is a real number, this simply returns ``self``.) 

  

EXAMPLES:: 

  

sage: RR(2).real() 

2.00000000000000 

sage: RealField(200)(-4.5).real() 

-4.5000000000000000000000000000000000000000000000000000000000 

""" 

return self 

  

def imag(self): 

""" 

Return the imaginary part of ``self``. 

  

(Since ``self`` is a real number, this simply returns exactly 0.) 

  

EXAMPLES:: 

  

sage: RR.pi().imag() 

0 

sage: RealField(100)(2).imag() 

0 

""" 

return ZZ(0) 

  

def str(self, int base=10, size_t digits=0, *, no_sci=None, 

e=None, bint truncate=False, bint skip_zeroes=False): 

""" 

Return a string representation of ``self``. 

  

INPUT: 

  

- ``base`` -- (default: 10) base for output 

  

- ``digits`` -- (default: 0) number of digits to display. When 

``digits`` is zero, choose this automatically. 

  

- ``no_sci`` -- if 2, never print using scientific notation; if 

``True``, use scientific notation only for very large or very 

small numbers; if ``False`` always print with scientific 

notation; if ``None`` (the default), print how the parent 

prints. 

  

- ``e`` -- symbol used in scientific notation; defaults to 'e' for 

base=10, and '@' otherwise 

  

- ``truncate`` -- (default: ``False``) if ``True``, round off the 

last digits in base-10 printing to lessen confusing base-2 

roundoff issues. This flag may not be used in other bases or 

when ``digits`` is given. 

  

- ``skip_zeroes`` -- (default: ``False``) if ``True``, skip 

trailing zeroes in mantissa 

  

EXAMPLES:: 

  

sage: a = 61/3.0; a 

20.3333333333333 

sage: a.str() 

'20.333333333333332' 

sage: a.str(truncate=True) 

'20.3333333333333' 

sage: a.str(2) 

'10100.010101010101010101010101010101010101010101010101' 

sage: a.str(no_sci=False) 

'2.0333333333333332e1' 

sage: a.str(16, no_sci=False) 

'1.4555555555555@1' 

sage: a.str(digits=5) 

'20.333' 

sage: a.str(2, digits=5) 

'10100.' 

  

sage: b = 2.0^99 

sage: b.str() 

'6.3382530011411470e29' 

sage: b.str(no_sci=False) 

'6.3382530011411470e29' 

sage: b.str(no_sci=True) 

'6.3382530011411470e29' 

sage: c = 2.0^100 

sage: c.str() 

'1.2676506002282294e30' 

sage: c.str(no_sci=False) 

'1.2676506002282294e30' 

sage: c.str(no_sci=True) 

'1.2676506002282294e30' 

sage: c.str(no_sci=2) 

'1267650600228229400000000000000.' 

sage: 0.5^53 

1.11022302462516e-16 

sage: 0.5^54 

5.55111512312578e-17 

sage: (0.01).str() 

'0.010000000000000000' 

sage: (0.01).str(skip_zeroes=True) 

'0.01' 

sage: (-10.042).str() 

'-10.042000000000000' 

sage: (-10.042).str(skip_zeroes=True) 

'-10.042' 

sage: (389.0).str(skip_zeroes=True) 

'389.' 

  

Test various bases:: 

  

sage: print((65536.0).str(base=2)) 

1.0000000000000000000000000000000000000000000000000000e16 

sage: print((65536.0).str(base=36)) 

1ekg.00000000 

sage: print((65536.0).str(base=62)) 

H32.0000000 

  

String conversion respects rounding:: 

  

sage: x = -RR.pi() 

sage: x.str(digits=1) 

'-3.' 

sage: y = RealField(53, rnd="RNDD")(x) 

sage: y.str(digits=1) 

'-4.' 

sage: y = RealField(53, rnd="RNDU")(x) 

sage: y.str(digits=1) 

'-3.' 

sage: y = RealField(53, rnd="RNDZ")(x) 

sage: y.str(digits=1) 

'-3.' 

sage: y = RealField(53, rnd="RNDA")(x) 

sage: y.str(digits=1) 

'-4.' 

  

TESTS:: 

  

sage: x = RR.pi() 

sage: x.str(base=1) 

Traceback (most recent call last): 

... 

ValueError: base (=1) must be an integer between 2 and 62 

sage: x.str(base=63) 

Traceback (most recent call last): 

... 

ValueError: base (=63) must be an integer between 2 and 62 

sage: x.str(digits=-10) 

Traceback (most recent call last): 

... 

OverflowError: can't convert negative value to size_t 

sage: x.str(base=16, truncate=True) 

Traceback (most recent call last): 

... 

ValueError: truncate is only supported in base 10 

sage: x.str(digits=10, truncate=True) 

Traceback (most recent call last): 

... 

ValueError: cannot truncate when digits is given 

""" 

if base < 2 or base > 62: 

raise ValueError("base (=%s) must be an integer between 2 and 62" % base) 

if mpfr_nan_p(self.value): 

if base >= 24: 

return "@NaN@" 

else: 

return "NaN" 

elif mpfr_inf_p(self.value): 

if mpfr_sgn(self.value) > 0: 

return "+infinity" 

else: 

return "-infinity" 

  

if e is None: 

if base > 10: 

e = '@' 

else: 

e = 'e' 

  

if truncate: 

if base != 10: 

raise ValueError("truncate is only supported in base 10") 

if digits: 

raise ValueError("cannot truncate when digits is given") 

# This computes digits = floor(log_{10}(2^(b-1))), 

# which is the number of *decimal* digits that are 

# "right", given that the last binary bit of the binary 

# number can be off. That is, if this real is within a 

# relative error of 2^(-b) of an exact decimal with 

# `digits` digits, that decimal will be returned. 

# This is equivalent to saying that exact decimals with 

# `digits` digits differ by at least 2*2^(-b) (relative). 

  

# (Depending on the precision and the exact number involved, 

# adjacent exact decimals can differ by far more than 2*2^(-b) 

# (relative).) 

  

# This avoids the confusion a lot of people have with the last 

# 1-2 binary digits being wrong due to rounding coming from 

# representing numbers in binary. 

digits = <size_t>(((<RealField_class>self._parent).__prec - 1) * 0.3010299956) 

if digits < 2: 

digits = 2 

  

sig_on() 

cdef char *s 

cdef mp_exp_t exponent 

s = mpfr_get_str(NULL, &exponent, base, digits, 

self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

if s is NULL: 

raise RuntimeError("unable to convert an mpfr number to a string") 

t = char_to_str(s) 

mpfr_free_str(s) 

  

if skip_zeroes: 

t = _re_skip_zeroes.match(t).group(1) 

  

if no_sci is None: 

no_sci = not (<RealField_class>self._parent).sci_not 

  

if no_sci is True and abs(exponent-1) >= 6: 

no_sci = False 

  

if not no_sci: 

if t[0] == "-": 

return "-%s.%s%s%s" % (t[1:2], t[2:], e, exponent-1) 

return "%s.%s%s%s" % (t[0], t[1:], e, exponent-1) 

  

lpad = '' 

  

if exponent <= 0: 

n = len(t) 

lpad = '0.' + '0'*abs(exponent) 

else: 

n = exponent 

  

if t[0] == '-': 

lpad = '-' + lpad 

t = t[1:] 

z = lpad + str(t[:n]) 

w = t[n:] 

  

if len(w) > 0 and '.' not in z: 

z = z + ".%s" % w 

elif exponent > 0: 

z = z + '0'*(n-len(t)) 

if '.' not in z: 

z = z + "." 

  

return z 

  

def hex(self): 

""" 

Return a hexadecimal floating-point representation of ``self``, in the 

style of C99 hexadecimal floating-point constants. 

  

EXAMPLES:: 

  

sage: RR(-1/3).hex() 

'-0x5.5555555555554p-4' 

sage: Reals(100)(123.456e789).hex() 

'0xf.721008e90630c8da88f44dd2p+2624' 

sage: (-0.).hex() 

'-0x0p+0' 

  

:: 

  

sage: [(a.hex(), float(a).hex()) for a in [.5, 1., 2., 16.]] 

[('0x8p-4', '0x1.0000000000000p-1'), 

('0x1p+0', '0x1.0000000000000p+0'), 

('0x2p+0', '0x1.0000000000000p+1'), 

('0x1p+4', '0x1.0000000000000p+4')] 

  

Special values:: 

  

sage: [RR(s).hex() for s in ['+inf', '-inf', 'nan']] 

['inf', '-inf', 'nan'] 

""" 

cdef char *s 

cdef int r 

sig_on() 

r = mpfr_asprintf(&s, "%Ra", self.value) 

sig_off() 

if r < 0: # MPFR free()s its buffer itself in this case 

raise RuntimeError("unable to convert an mpfr number to a string") 

t = char_to_str(s) 

mpfr_free_str(s) 

return t 

  

def __hex__(self): 

""" 

TESTS:: 

  

sage: hex(RR(-1/3)) # py2 

doctest:...: 

DeprecationWarning: use the method .hex instead 

See http://trac.sagemath.org/24568 for details. 

'-0x5.5555555555554p-4' 

""" 

deprecation(24568, 'use the method .hex instead') 

return self.hex() 

  

def __copy__(self): 

""" 

Return copy of ``self`` - since ``self`` is immutable, we just return 

``self`` again. 

  

EXAMPLES:: 

  

sage: a = 3.5 

sage: copy(a) is a 

True 

""" 

return self # since object is immutable. 

  

def _integer_(self, Z=None): 

""" 

If this floating-point number is actually an integer, return that 

integer. Otherwise, raise an exception. 

  

EXAMPLES:: 

  

sage: ZZ(237.0) # indirect doctest 

237 

sage: ZZ(0.0/0.0) 

Traceback (most recent call last): 

... 

TypeError: Attempt to coerce non-integral RealNumber to Integer 

sage: ZZ(1.0/0.0) 

Traceback (most recent call last): 

... 

TypeError: Attempt to coerce non-integral RealNumber to Integer 

sage: ZZ(-123456789.0) 

-123456789 

sage: ZZ(RealField(300)(2.0)^290) 

1989292945639146568621528992587283360401824603189390869761855907572637988050133502132224 

sage: ZZ(-2345.67) 

Traceback (most recent call last): 

... 

TypeError: Attempt to coerce non-integral RealNumber to Integer 

""" 

cdef Integer n 

  

if mpfr_integer_p(self.value): 

n = PY_NEW(Integer) 

mpfr_get_z(n.value, self.value, MPFR_RNDN) 

return n 

  

raise TypeError("Attempt to coerce non-integral RealNumber to Integer") 

  

def integer_part(self): 

""" 

If in decimal this number is written ``n.defg``, returns ``n``. 

  

OUTPUT: a Sage Integer 

  

EXAMPLES:: 

  

sage: a = 119.41212 

sage: a.integer_part() 

119 

sage: a = -123.4567 

sage: a.integer_part() 

-123 

  

A big number with no decimal point:: 

  

sage: a = RR(10^17); a 

1.00000000000000e17 

sage: a.integer_part() 

100000000000000000 

""" 

if not mpfr_number_p(self.value): 

raise ValueError('Cannot convert infinity or NaN to Sage Integer') 

  

cdef Integer z = Integer() 

mpfr_get_z(z.value, self.value, MPFR_RNDZ) 

return z 

  

def fp_rank(self): 

r""" 

Returns the floating-point rank of this number. That is, if you 

list the floating-point numbers of this precision in order, and 

number them starting with `0.0 \rightarrow 0` and extending 

the list to positive and negative infinity, returns the number 

corresponding to this floating-point number. 

  

EXAMPLES:: 

  

sage: RR(0).fp_rank() 

0 

sage: RR(0).nextabove().fp_rank() 

1 

sage: RR(0).nextbelow().nextbelow().fp_rank() 

-2 

sage: RR(1).fp_rank() 

4835703278458516698824705 # 32-bit 

20769187434139310514121985316880385 # 64-bit 

sage: RR(-1).fp_rank() 

-4835703278458516698824705 # 32-bit 

-20769187434139310514121985316880385 # 64-bit 

sage: RR(1).fp_rank() - RR(1).nextbelow().fp_rank() 

1 

sage: RR(-infinity).fp_rank() 

-9671406552413433770278913 # 32-bit 

-41538374868278621023740371006390273 # 64-bit 

sage: RR(-infinity).fp_rank() - RR(-infinity).nextabove().fp_rank() 

-1 

""" 

if mpfr_nan_p(self.value): 

raise ValueError("Cannot compute fp_rank of NaN") 

  

cdef Integer z = PY_NEW(Integer) 

  

cdef mp_exp_t EXP_MIN = mpfr_get_exp_min() 

cdef mp_exp_t EXP_MAX = mpfr_get_exp_max() 

# fp_rank(0.0) = 0 

# fp_rank(m*2^e-p) = (m-2^{p-1})+(e-EXP_MIN)*2^{p-1}+1 

# = m+(e-EXP_MIN-1)*2^{p-1}+1 

# fp_rank(infinity) = (EXP_MAX+1-EXP_MIN)*2^{p-1}+1 

# fp_rank(-x) = -fp_rank(x) 

  

cdef int sgn = mpfr_sgn(self.value) 

  

if sgn == 0: 

return z 

  

cdef int prec = (<RealField_class>self._parent).__prec 

  

if mpfr_inf_p(self.value): 

mpz_set_ui(z.value, EXP_MAX+1-EXP_MIN) 

mpz_mul_2exp(z.value, z.value, prec-1) 

mpz_add_ui(z.value, z.value, 1) 

if sgn < 0: 

mpz_neg(z.value, z.value) 

return z 

  

cdef mpz_t mantissa 

mpz_init(mantissa) 

cdef mp_exp_t exponent = mpfr_get_z_exp(mantissa, self.value) 

mpz_set_si(z.value, exponent+prec-EXP_MIN-1) 

mpz_mul_2exp(z.value, z.value, prec-1) 

mpz_add_ui(z.value, z.value, 1) 

if sgn > 0: 

mpz_add(z.value, z.value, mantissa) 

else: 

mpz_sub(z.value, z.value, mantissa) 

mpz_neg(z.value, z.value) 

mpz_clear(mantissa) 

return z 

  

def fp_rank_delta(self, RealNumber other): 

r""" 

Return the floating-point rank delta between ``self`` 

and ``other``. That is, if the return value is 

positive, this is the number of times you have to call 

``.nextabove()`` to get from ``self`` to ``other``. 

  

EXAMPLES:: 

  

sage: [x.fp_rank_delta(x.nextabove()) for x in 

....: (RR(-infinity), -1.0, 0.0, 1.0, RR(pi), RR(infinity))] 

[1, 1, 1, 1, 1, 0] 

  

In the 2-bit floating-point field, one subsegment of the 

floating-point numbers is: 1, 1.5, 2, 3, 4, 6, 8, 12, 16, 24, 32 

  

:: 

  

sage: R2 = RealField(2) 

sage: R2(1).fp_rank_delta(R2(2)) 

2 

sage: R2(2).fp_rank_delta(R2(1)) 

-2 

sage: R2(1).fp_rank_delta(R2(1048576)) 

40 

sage: R2(24).fp_rank_delta(R2(4)) 

-5 

sage: R2(-4).fp_rank_delta(R2(-24)) 

-5 

  

There are lots of floating-point numbers around 0:: 

  

sage: R2(-1).fp_rank_delta(R2(1)) 

4294967298 # 32-bit 

18446744073709551618 # 64-bit 

""" 

# We create the API for forward compatibility, because it can have 

# a (somewhat) more efficient implementation than this; but for now, 

# we just go with the stupid implementation. 

return other.fp_rank() - self.fp_rank() 

  

######################## 

# Basic Arithmetic 

######################## 

  

cpdef _add_(self, other): 

""" 

Add two real numbers with the same parent. 

  

EXAMPLES:: 

  

sage: R = RealField() 

sage: R(-1.5) + R(2.5) # indirect doctest 

1.00000000000000 

""" 

cdef RealNumber x = self._new() 

mpfr_add(x.value, self.value, (<RealNumber>other).value, (<RealField_class>self._parent).rnd) 

return x 

  

def __invert__(self): 

""" 

Return the reciprocal of ``self``. 

  

EXAMPLES:: 

  

sage: ~RR(5/2) 

0.400000000000000 

sage: ~RR(1) 

1.00000000000000 

sage: ~RR(0) 

+infinity 

""" 

return self._parent(1) / self 

  

cpdef _sub_(self, right): 

""" 

Subtract two real numbers with the same parent. 

  

EXAMPLES:: 

  

sage: R = RealField() 

sage: R(-1.5) - R(2.5) # indirect doctest 

-4.00000000000000 

""" 

cdef RealNumber x = self._new() 

mpfr_sub(x.value, self.value, (<RealNumber>right).value, (<RealField_class> self._parent).rnd) 

return x 

  

def _sympy_(self): 

""" 

Return a sympy object of ``self``. 

  

EXAMPLES: 

  

An indirect doctest to check this (see :trac:`14915`):: 

  

sage: x,y = var('x, y') 

sage: integrate(y, y, 0.5, 8*log(x), algorithm='sympy') 

32*log(x)^2 - 0.125000000000000 

  

""" 

from sympy import simplify 

return simplify(float(self)) 

  

cpdef _mul_(self, right): 

""" 

Multiply two real numbers with the same parent. 

  

EXAMPLES:: 

  

sage: R = RealField() 

sage: R(-1.5) * R(2.5) # indirect doctest 

-3.75000000000000 

  

If two elements have different precision, arithmetic operations are 

performed after coercing to the lower precision:: 

  

sage: R20 = RealField(20) 

sage: R100 = RealField(100) 

sage: a = R20('393.3902834028345') 

sage: b = R100('393.3902834028345') 

sage: a 

393.39 

sage: b 

393.39028340283450000000000000 

sage: a*b 

154760. 

sage: b*a 

154760. 

sage: parent(b*a) 

Real Field with 20 bits of precision 

""" 

cdef RealNumber x = self._new() 

mpfr_mul(x.value, self.value, (<RealNumber>right).value, (<RealField_class>self._parent).rnd) 

return x 

  

  

cpdef _div_(self, right): 

""" 

Divide ``self`` by other, where both are real numbers with the same 

parent. 

  

EXAMPLES:: 

  

sage: RR(1)/RR(3) # indirect doctest 

0.333333333333333 

sage: RR(1)/RR(0) 

+infinity 

sage: R = RealField() 

sage: R(-1.5) / R(2.5) 

-0.600000000000000 

""" 

cdef RealNumber x = self._new() 

mpfr_div((<RealNumber>x).value, self.value, 

(<RealNumber>right).value, (<RealField_class>self._parent).rnd) 

return x 

  

cpdef _neg_(self): 

""" 

Return the negative of ``self``. 

  

EXAMPLES:: 

  

sage: RR(1)._neg_() 

-1.00000000000000 

sage: RR('inf')._neg_() 

-infinity 

sage: RR('nan')._neg_() 

NaN 

""" 

cdef RealNumber x = self._new() 

mpfr_neg(x.value, self.value, (<RealField_class>self._parent).rnd) 

return x 

  

def __abs__(self): 

""" 

Return the absolute value of ``self``. 

  

EXAMPLES:: 

  

sage: RR(-1).__abs__() 

1.00000000000000 

sage: RR('-inf').__abs__() 

+infinity 

sage: RR('inf').__abs__() 

+infinity 

sage: RR('nan').__abs__() 

NaN 

""" 

return self.abs() 

  

cdef RealNumber abs(RealNumber self): 

""" 

Return the absolute value of ``self``. 

  

EXAMPLES:: 

  

sage: RR('-1').abs() 

1.00000000000000 

sage: RR('-inf').abs() 

+infinity 

sage: RR('inf').abs() 

+infinity 

sage: RR('nan').abs() 

NaN 

""" 

cdef RealNumber x = self._new() 

mpfr_abs(x.value, self.value, (<RealField_class>self._parent).rnd) 

return x 

  

# Bit shifting 

def _lshift_(RealNumber self, n): 

""" 

Return ``self * (2^n)`` for an integer ``n``. 

  

EXAMPLES:: 

  

sage: RR(1.0)._lshift_(32) 

4.29496729600000e9 

sage: RR(1.5)._lshift_(2) 

6.00000000000000 

""" 

cdef RealNumber x 

if n > sys.maxsize: 

raise OverflowError("n (=%s) must be <= %s" % (n, sys.maxsize)) 

x = self._new() 

mpfr_mul_2ui(x.value, self.value, n, (<RealField_class>self._parent).rnd) 

return x 

  

def __lshift__(x, y): 

""" 

Return ``self * (2^n)`` for an integer ``n``. 

  

EXAMPLES:: 

  

sage: 1.0 << 32 

4.29496729600000e9 

sage: 1.5 << 2.5 

Traceback (most recent call last): 

... 

TypeError: unsupported operands for << 

""" 

if not isinstance(x, RealNumber): 

raise TypeError("unsupported operands for <<") 

try: 

return x._lshift_(Integer(y)) 

except TypeError: 

raise TypeError("unsupported operands for <<") 

  

def _rshift_(RealNumber self, n): 

""" 

Return ``self / (2^n)`` for an integer ``n``. 

  

EXAMPLES:: 

  

sage: RR(1.0)._rshift_(32) 

2.32830643653870e-10 

sage: RR(1.5)._rshift_(2) 

0.375000000000000 

""" 

if n > sys.maxsize: 

raise OverflowError("n (=%s) must be <= %s" % (n, sys.maxsize)) 

cdef RealNumber x = self._new() 

mpfr_div_2exp(x.value, self.value, n, (<RealField_class>self._parent).rnd) 

return x 

  

def __rshift__(x, y): 

""" 

Return ``self / (2^n)`` for an integer ``n``. 

  

EXAMPLES:: 

  

sage: 1024.0 >> 7 

8.00000000000000 

sage: 1.5 >> 2.5 

Traceback (most recent call last): 

... 

TypeError: unsupported operands for >> 

""" 

if not isinstance(x, RealNumber): 

raise TypeError("unsupported operands for >>") 

try: 

return x._rshift_(Integer(y)) 

except TypeError: 

raise TypeError("unsupported operands for >>") 

  

  

def multiplicative_order(self): 

""" 

Return the multiplicative order of ``self``. 

  

EXAMPLES:: 

  

sage: RR(1).multiplicative_order() 

1 

sage: RR(-1).multiplicative_order() 

2 

sage: RR(3).multiplicative_order() 

+Infinity 

""" 

  

if self == 1: 

return 1 

elif self == -1: 

return 2 

return sage.rings.infinity.infinity 

  

def sign(self): 

""" 

Return ``+1`` if ``self`` is positive, ``-1`` if ``self`` is negative, 

and ``0`` if ``self`` is zero. 

  

EXAMPLES:: 

  

sage: R=RealField(100) 

sage: R(-2.4).sign() 

-1 

sage: R(2.1).sign() 

1 

sage: R(0).sign() 

0 

""" 

return mpfr_sgn(self.value) 

  

def precision(self): 

""" 

Return the precision of ``self``. 

  

EXAMPLES:: 

  

sage: RR(1.0).precision() 

53 

sage: RealField(101)(-1).precision() 

101 

""" 

return (<RealField_class>self._parent).__prec 

  

prec = precision # alias 

  

def conjugate(self): 

""" 

Return the complex conjugate of this real number, which is the 

number itself. 

  

EXAMPLES:: 

  

sage: x = RealField(100)(1.238) 

sage: x.conjugate() 

1.2380000000000000000000000000 

""" 

return self 

  

def ulp(self, field=None): 

""" 

Returns the unit of least precision of ``self``, which is the 

weight of the least significant bit of ``self``. This is always 

a strictly positive number. It is also the gap between this 

number and the closest number with larger absolute value that 

can be represented. 

  

INPUT: 

  

- ``field`` -- :class:`RealField` used as parent of the result. 

If not specified, use ``parent(self)``. 

  

.. NOTE:: 

  

The ulp of zero is defined as the smallest representable 

positive number. For extremely small numbers, underflow 

occurs and the output is also the smallest representable 

positive number (the rounding mode is ignored, this 

computation is done by rounding towards +infinity). 

  

.. SEEALSO:: 

  

:meth:`epsilon` for a scale-invariant version of this. 

  

EXAMPLES:: 

  

sage: a = 1.0 

sage: a.ulp() 

2.22044604925031e-16 

sage: (-1.5).ulp() 

2.22044604925031e-16 

sage: a + a.ulp() == a 

False 

sage: a + a.ulp()/2 == a 

True 

  

sage: a = RealField(500).pi() 

sage: b = a + a.ulp() 

sage: (a+b)/2 in [a,b] 

True 

  

The ulp of zero is the smallest non-zero number:: 

  

sage: a = RR(0).ulp() 

sage: a 

2.38256490488795e-323228497 # 32-bit 

8.50969131174084e-1388255822130839284 # 64-bit 

sage: a.fp_rank() 

1 

  

The ulp of very small numbers results in underflow, so the 

smallest non-zero number is returned instead:: 

  

sage: a.ulp() == a 

True 

  

We use a different field:: 

  

sage: a = RealField(256).pi() 

sage: a.ulp() 

3.454467422037777850154540745120159828446400145774512554009481388067436721265e-77 

sage: e = a.ulp(RealField(64)) 

sage: e 

3.45446742203777785e-77 

sage: parent(e) 

Real Field with 64 bits of precision 

sage: e = a.ulp(QQ) 

Traceback (most recent call last): 

... 

TypeError: field argument must be a RealField 

  

For infinity and NaN, we get back positive infinity and NaN:: 

  

sage: a = RR(infinity) 

sage: a.ulp() 

+infinity 

sage: (-a).ulp() 

+infinity 

sage: a = RR('nan') 

sage: a.ulp() 

NaN 

sage: parent(RR('nan').ulp(RealField(42))) 

Real Field with 42 bits of precision 

""" 

cdef RealField_class _parent 

if field is None: 

_parent = self._parent 

else: 

try: 

_parent = field 

except TypeError: 

raise TypeError("field argument must be a RealField") 

  

cdef RealNumber x = _parent._new() 

cdef mp_exp_t e 

if mpfr_regular_p(self.value): 

# Non-zero number 

e = mpfr_get_exp(self.value) - mpfr_get_prec(self.value) 

# Round up in case of underflow 

mpfr_set_ui_2exp(x.value, 1, e, MPFR_RNDU) 

else: 

# Special cases: zero, infinity, NaN 

if mpfr_zero_p(self.value): 

mpfr_set_zero(x.value, 1) 

mpfr_nextabove(x.value) 

elif mpfr_inf_p(self.value): 

mpfr_set_inf(x.value, 1) 

else: # NaN 

mpfr_set_nan(x.value) 

return x 

  

def epsilon(self, field=None): 

""" 

Returns ``abs(self)`` divided by `2^b` where `b` is the 

precision in bits of ``self``. Equivalently, return 

``abs(self)`` multiplied by the :meth:`ulp` of 1. 

  

This is a scale-invariant version of :meth:`ulp` and it lies 

in `[u/2, u)` where `u` is ``self.ulp()`` (except in the case 

of zero or underflow). 

  

INPUT: 

  

- ``field`` -- :class:`RealField` used as parent of the result. 

If not specified, use ``parent(self)``. 

  

OUTPUT: 

  

``field(self.abs() / 2^self.precision())`` 

  

EXAMPLES:: 

  

sage: RR(2^53).epsilon() 

1.00000000000000 

sage: RR(0).epsilon() 

0.000000000000000 

sage: a = RR.pi() 

sage: a.epsilon() 

3.48786849800863e-16 

sage: a.ulp()/2, a.ulp() 

(2.22044604925031e-16, 4.44089209850063e-16) 

sage: a / 2^a.precision() 

3.48786849800863e-16 

sage: (-a).epsilon() 

3.48786849800863e-16 

  

We use a different field:: 

  

sage: a = RealField(256).pi() 

sage: a.epsilon() 

2.713132368784788677624750042896586252980746500631892201656843478528498954308e-77 

sage: e = a.epsilon(RealField(64)) 

sage: e 

2.71313236878478868e-77 

sage: parent(e) 

Real Field with 64 bits of precision 

sage: e = a.epsilon(QQ) 

Traceback (most recent call last): 

... 

TypeError: field argument must be a RealField 

  

Special values:: 

  

sage: RR('nan').epsilon() 

NaN 

sage: parent(RR('nan').epsilon(RealField(42))) 

Real Field with 42 bits of precision 

sage: RR('+Inf').epsilon() 

+infinity 

sage: RR('-Inf').epsilon() 

+infinity 

""" 

cdef RealField_class _parent 

if field is None: 

_parent = self._parent 

else: 

try: 

_parent = field 

except TypeError: 

raise TypeError("field argument must be a RealField") 

  

cdef RealNumber x = _parent._new() 

mpfr_div_2exp(x.value, self.value, mpfr_get_prec(self.value), _parent.rnd) 

mpfr_abs(x.value, x.value, _parent.rnd) 

return x 

  

  

################### 

# Rounding etc 

################### 

  

cpdef _mod_(left, right): 

""" 

Return the value of ``left - n*right``, rounded according to the 

rounding mode of the parent, where ``n`` is the integer quotient of 

``x`` divided by ``y``. The integer ``n`` is rounded toward the 

nearest integer (ties rounded to even). 

  

EXAMPLES:: 

  

sage: 10.0 % 2r 

0.000000000000000 

sage: 20r % .5 

0.000000000000000 

  

sage 1.1 % 0.25 

0.100000000000000 

""" 

cdef RealNumber x 

x = (<RealNumber>left)._new() 

mpfr_remainder (x.value, (<RealNumber>left).value, 

(<RealNumber>right).value, 

(<RealField_class>(<RealNumber>left)._parent).rnd) 

return x 

  

def round(self): 

""" 

Rounds ``self`` to the nearest integer. The rounding mode of the 

parent field has no effect on this function. 

  

EXAMPLES:: 

  

sage: RR(0.49).round() 

0 

sage: RR(0.5).round() 

1 

sage: RR(-0.49).round() 

0 

sage: RR(-0.5).round() 

-1 

""" 

cdef RealNumber x = self._new() 

mpfr_round(x.value, self.value) 

return x.integer_part() 

  

def floor(self): 

""" 

Return the floor of ``self``. 

  

EXAMPLES:: 

  

sage: R = RealField() 

sage: (2.99).floor() 

2 

sage: (2.00).floor() 

2 

sage: floor(RR(-5/2)) 

-3 

sage: floor(RR(+infinity)) 

Traceback (most recent call last): 

... 

ValueError: Calling floor() on infinity or NaN 

""" 

cdef RealNumber x 

if not mpfr_number_p(self.value): 

raise ValueError('Calling floor() on infinity or NaN') 

x = self._new() 

mpfr_floor(x.value, self.value) 

return x.integer_part() 

  

def ceil(self): 

""" 

Return the ceiling of ``self``. 

  

EXAMPLES:: 

  

sage: (2.99).ceil() 

3 

sage: (2.00).ceil() 

2 

sage: (2.01).ceil() 

3 

  

:: 

  

sage: ceil(10^16 * 1.0) 

10000000000000000 

sage: ceil(10^17 * 1.0) 

100000000000000000 

sage: ceil(RR(+infinity)) 

Traceback (most recent call last): 

... 

ValueError: Calling ceil() on infinity or NaN 

""" 

cdef RealNumber x 

if not mpfr_number_p(self.value): 

raise ValueError('Calling ceil() on infinity or NaN') 

x = self._new() 

mpfr_ceil(x.value, self.value) 

return x.integer_part() 

  

ceiling = ceil # alias 

  

def trunc(self): 

""" 

Truncate ``self``. 

  

EXAMPLES:: 

  

sage: (2.99).trunc() 

2 

sage: (-0.00).trunc() 

0 

sage: (0.00).trunc() 

0 

""" 

cdef RealNumber x = self._new() 

mpfr_trunc(x.value, self.value) 

return x.integer_part() 

  

def frac(self): 

""" 

Return a real number such that 

``self = self.trunc() + self.frac()``. The return value will also 

satisfy ``-1 < self.frac() < 1``. 

  

EXAMPLES:: 

  

sage: (2.99).frac() 

0.990000000000000 

sage: (2.50).frac() 

0.500000000000000 

sage: (-2.79).frac() 

-0.790000000000000 

sage: (-2.79).trunc() + (-2.79).frac() 

-2.79000000000000 

""" 

cdef RealNumber x 

x = self._new() 

mpfr_frac(x.value, self.value, (<RealField_class>self._parent).rnd) 

return x 

  

def nexttoward(self, other): 

""" 

Return the floating-point number adjacent to ``self`` which is closer 

to ``other``. If ``self`` or other is ``NaN``, returns ``NaN``; if 

``self`` equals ``other``, returns ``self``. 

  

EXAMPLES:: 

  

sage: (1.0).nexttoward(2).str() 

'1.0000000000000002' 

sage: (1.0).nexttoward(RR('-infinity')).str() 

'0.99999999999999989' 

sage: RR(infinity).nexttoward(0) 

2.09857871646739e323228496 # 32-bit 

5.87565378911159e1388255822130839282 # 64-bit 

sage: RR(pi).str() 

'3.1415926535897931' 

sage: RR(pi).nexttoward(22/7).str() 

'3.1415926535897936' 

sage: RR(pi).nexttoward(21/7).str() 

'3.1415926535897927' 

""" 

cdef RealNumber other_rn 

if isinstance(other, RealNumber): 

other_rn = other 

else: 

other_rn = self._parent(other) 

  

cdef RealNumber x = self._new() 

  

mpfr_set(x.value, self.value, MPFR_RNDN) 

mpfr_nexttoward(x.value, other_rn.value) 

  

return x 

  

def nextabove(self): 

""" 

Return the next floating-point number larger than ``self``. 

  

EXAMPLES:: 

  

sage: RR('-infinity').nextabove() 

-2.09857871646739e323228496 # 32-bit 

-5.87565378911159e1388255822130839282 # 64-bit 

sage: RR(0).nextabove() 

2.38256490488795e-323228497 # 32-bit 

8.50969131174084e-1388255822130839284 # 64-bit 

sage: RR('+infinity').nextabove() 

+infinity 

sage: RR(-sqrt(2)).str() 

'-1.4142135623730951' 

sage: RR(-sqrt(2)).nextabove().str() 

'-1.4142135623730949' 

""" 

  

cdef RealNumber x = self._new() 

mpfr_set(x.value, self.value, MPFR_RNDN) 

mpfr_nextabove(x.value) 

  

return x 

  

def nextbelow(self): 

""" 

Return the next floating-point number smaller than ``self``. 

  

EXAMPLES:: 

  

sage: RR('-infinity').nextbelow() 

-infinity 

sage: RR(0).nextbelow() 

-2.38256490488795e-323228497 # 32-bit 

-8.50969131174084e-1388255822130839284 # 64-bit 

sage: RR('+infinity').nextbelow() 

2.09857871646739e323228496 # 32-bit 

5.87565378911159e1388255822130839282 # 64-bit 

sage: RR(-sqrt(2)).str() 

'-1.4142135623730951' 

sage: RR(-sqrt(2)).nextbelow().str() 

'-1.4142135623730954' 

""" 

  

cdef RealNumber x = self._new() 

mpfr_set(x.value, self.value, MPFR_RNDN) 

mpfr_nextbelow(x.value) 

  

return x 

  

########################################### 

# Conversions 

########################################### 

  

def __float__(self): 

""" 

Return a Python float approximating ``self``. 

  

EXAMPLES:: 

  

sage: RR(pi).__float__() 

3.141592653589793 

sage: type(RR(pi).__float__()) 

<... 'float'> 

""" 

return mpfr_get_d(self.value, (<RealField_class>self._parent).rnd) 

  

def _rpy_(self): 

""" 

Return ``self.__float__()`` for rpy to convert into the 

appropriate R object. 

  

EXAMPLES:: 

  

sage: n = RealNumber(2.0) 

sage: n._rpy_() 

2.0 

sage: type(n._rpy_()) 

<... 'float'> 

""" 

return self.__float__() 

  

def __int__(self): 

""" 

Return the Python integer truncation of ``self``. 

  

EXAMPLES:: 

  

sage: RR(pi).__int__() 

3 

sage: type(RR(pi).__int__()) 

<... 'int'> 

""" 

if not mpfr_number_p(self.value): 

raise ValueError('Cannot convert infinity or NaN to Python int') 

  

cdef Integer z = Integer() 

mpfr_get_z(z.value, self.value, MPFR_RNDZ) 

return z.__int__() 

  

def __long__(self): 

""" 

Returns Python long integer truncation of this real number. 

  

EXAMPLES:: 

  

sage: long(RR(pi)) 

3L 

""" 

if not mpfr_number_p(self.value): 

raise ValueError('Cannot convert infinity or NaN to Python long') 

  

cdef Integer z = Integer() 

mpfr_get_z(z.value, self.value, MPFR_RNDZ) 

return z.__long__() 

  

def __complex__(self): 

""" 

Return a Python complex number equal to ``self``. 

  

EXAMPLES:: 

  

sage: RR(pi).__complex__() 

(3.141592653589793+0j) 

sage: type(RR(pi).__complex__()) 

<... 'complex'> 

""" 

  

return complex(float(self)) 

  

def _complex_number_(self): 

""" 

Return a Sage complex number equal to ``self``. 

  

EXAMPLES:: 

  

sage: RR(pi)._complex_number_() 

3.14159265358979 

sage: parent(RR(pi)._complex_number_()) 

Complex Field with 53 bits of precision 

""" 

from sage.rings.complex_field import ComplexField 

return ComplexField(self.prec())(self) 

  

def _axiom_(self, axiom): 

""" 

Return ``self`` as a floating point number in Axiom. 

  

EXAMPLES:: 

  

sage: R = RealField(100) 

sage: R(pi) 

3.1415926535897932384626433833 

sage: axiom(R(pi)) # optional - axiom # indirect doctest 

3.1415926535 8979323846 26433833 

sage: fricas(R(pi)) # optional - fricas 

3.1415926535_8979323846_26433833 

  

""" 

prec = self.parent().prec() 

  

#Set the precision in Axiom 

old_prec = axiom('precision(%s)$Float'%prec) 

res = axiom('%s :: Float'%self.exact_rational()) 

axiom.eval('precision(%s)$Float'%old_prec) 

  

return res 

  

_fricas_ = _axiom_ 

  

def __pari__(self): 

""" 

Return ``self`` as a Pari floating-point number. 

  

EXAMPLES:: 

  

sage: RR(2.0).__pari__() 

2.00000000000000 

  

The current Pari precision affects the printing of this number, but 

Pari does maintain the same 250-bit number on both 32-bit and 

64-bit platforms:: 

  

sage: RealField(250).pi().__pari__() 

3.14159265358979 

sage: RR(0.0).__pari__() 

0.E-19 

sage: RR(-1.234567).__pari__() 

-1.23456700000000 

sage: RR(2.0).sqrt().__pari__() 

1.41421356237310 

sage: RR(2.0).sqrt().__pari__().sage() 

1.41421356237309515 

sage: RR(2.0).sqrt().__pari__().sage().prec() 

64 

sage: RealField(70)(pi).__pari__().sage().prec() 

96 # 32-bit 

128 # 64-bit 

sage: for i in range(100, 200): 

....: assert(RR(i).sqrt() == RR(i).sqrt().__pari__().sage()) 

  

TESTS: 

  

Check that we create real zeros without mantissa:: 

  

sage: RDF(0).__pari__().sizeword() 

2 

sage: RealField(100)(0.0).__pari__().sizeword() 

2 

  

Check that the largest and smallest exponents representable by 

PARI convert correctly:: 

  

sage: a = pari(0.5) << (sys.maxsize+1)/4 

sage: RR(a) >> (sys.maxsize+1)/4 

0.500000000000000 

sage: a = pari(0.5) >> (sys.maxsize-3)/4 

sage: RR(a) << (sys.maxsize-3)/4 

0.500000000000000 

""" 

# This uses interfaces of MPFR and PARI which are documented 

# (and not marked subject-to-change). It could be faster 

# by using internal interfaces of MPFR, which are documented 

# as subject-to-change. 

  

sig_on() 

if mpfr_nan_p(self.value) or mpfr_inf_p(self.value): 

raise ValueError('Cannot convert NaN or infinity to Pari float') 

  

# wordsize for PARI 

cdef unsigned long wordsize = sizeof(long)*8 

  

cdef int prec 

prec = (<RealField_class>self._parent).__prec 

  

# We round up the precision to the nearest multiple of wordsize. 

cdef int rounded_prec 

rounded_prec = (self.prec() + wordsize - 1) & ~(wordsize - 1) 

  

# Yes, assigning to self works fine, even in Cython. 

if rounded_prec > prec: 

self = RealField(rounded_prec)(self) 

  

cdef mpz_t mantissa 

cdef mp_exp_t exponent 

cdef GEN pari_float 

  

if mpfr_zero_p(self.value): 

pari_float = real_0_bit(-rounded_prec) 

else: 

# Now we can extract the mantissa, and it will be normalized 

# (the most significant bit of the most significant word will be 1). 

mpz_init(mantissa) 

exponent = mpfr_get_z_exp(mantissa, self.value) 

  

# Create a PARI REAL 

pari_float = cgetr(2 + rounded_prec / wordsize) 

pari_float[1] = evalexpo(exponent + rounded_prec - 1) + evalsigne(mpfr_sgn(self.value)) 

mpz_export(&pari_float[2], NULL, 1, wordsize/8, 0, 0, mantissa) 

mpz_clear(mantissa) 

  

return new_gen(pari_float) 

  

def _mpmath_(self, prec=None, rounding=None): 

""" 

Return an mpmath version of this :class:`RealNumber`. 

  

.. NOTE:: 

  

Currently the rounding mode is ignored. 

  

EXAMPLES:: 

  

sage: RR(-1.5)._mpmath_() 

mpf('-1.5') 

""" 

if prec is not None: 

return RealField(prec)(self)._mpmath_() 

from sage.libs.mpmath.all import make_mpf 

return make_mpf(mpfr_to_mpfval(self.value)) 

  

  

def sign_mantissa_exponent(self): 

r""" 

Return the sign, mantissa, and exponent of ``self``. 

  

In Sage (as in MPFR), floating-point numbers of precision `p` 

are of the form `s m 2^{e-p}`, where `s \in \{-1, 1\}`, 

`2^{p-1} \leq m < 2^p`, and `-2^{30} + 1 \leq e \leq 2^{30} - 

1`; plus the special values ``+0``, ``-0``, ``+infinity``, 

``-infinity``, and ``NaN`` (which stands for Not-a-Number). 

  

This function returns `s`, `m`, and `e-p`. For the special values: 

  

- ``+0`` returns ``(1, 0, 0)`` (analogous to IEEE-754; 

note that MPFR actually stores the exponent as "smallest exponent 

possible") 

- ``-0`` returns ``(-1, 0, 0)`` (analogous to IEEE-754; 

note that MPFR actually stores the exponent as "smallest exponent 

possible") 

- the return values for ``+infinity``, ``-infinity``, and ``NaN`` are 

not specified. 

  

EXAMPLES:: 

  

sage: R = RealField(53) 

sage: a = R(exp(1.0)); a 

2.71828182845905 

sage: sign, mantissa, exponent = R(exp(1.0)).sign_mantissa_exponent() 

sage: sign, mantissa, exponent 

(1, 6121026514868073, -51) 

sage: sign*mantissa*(2**exponent) == a 

True 

  

The mantissa is always a nonnegative number (see :trac:`14448`):: 

  

sage: RR(-1).sign_mantissa_exponent() 

(-1, 4503599627370496, -52) 

  

We can also calculate this also using `p`-adic valuations:: 

  

sage: a = R(exp(1.0)) 

sage: b = a.exact_rational() 

sage: valuation, unit = b.val_unit(2) 

sage: (b/abs(b), unit, valuation) 

(1, 6121026514868073, -51) 

sage: a.sign_mantissa_exponent() 

(1, 6121026514868073, -51) 

  

TESTS:: 

  

sage: R('+0').sign_mantissa_exponent() 

(1, 0, 0) 

sage: R('-0').sign_mantissa_exponent() 

(-1, 0, 0) 

""" 

cdef Integer mantissa 

cdef Integer sign 

cdef mp_exp_t exponent 

  

  

if mpfr_signbit(self.value)==0: 

sign=Integer(1) 

else: 

sign=Integer(-1) 

  

if mpfr_zero_p(self.value): 

mantissa=Integer(0) 

exponent=Integer(0) 

else: 

mantissa = Integer() 

exponent = mpfr_get_z_exp(mantissa.value, self.value) 

  

return sign, sign*mantissa, Integer(exponent) 

  

def exact_rational(self): 

""" 

Returns the exact rational representation of this floating-point 

number. 

  

EXAMPLES:: 

  

sage: RR(0).exact_rational() 

0 

sage: RR(1/3).exact_rational() 

6004799503160661/18014398509481984 

sage: RR(37/16).exact_rational() 

37/16 

sage: RR(3^60).exact_rational() 

42391158275216203520420085760 

sage: RR(3^60).exact_rational() - 3^60 

6125652559 

sage: RealField(5)(-pi).exact_rational() 

-25/8 

  

TESTS:: 

  

sage: RR('nan').exact_rational() 

Traceback (most recent call last): 

... 

ValueError: Cannot convert NaN or infinity to rational number 

sage: RR('-infinity').exact_rational() 

Traceback (most recent call last): 

... 

ValueError: Cannot convert NaN or infinity to rational number 

""" 

if not mpfr_number_p(self.value): 

raise ValueError('Cannot convert NaN or infinity to rational number') 

  

cdef Integer mantissa = Integer() 

cdef mp_exp_t exponent 

  

if mpfr_sgn(self.value) == 0: 

return Rational(0) 

  

exponent = mpfr_get_z_exp(mantissa.value, self.value) 

  

return Rational(mantissa) * Integer(2) ** exponent 

  

def simplest_rational(self): 

""" 

Return the simplest rational which is equal to ``self`` (in the Sage 

sense). Recall that Sage defines the equality operator by coercing 

both sides to a single type and then comparing; thus, this finds 

the simplest rational which (when coerced to this RealField) is 

equal to ``self``. 

  

Given rationals `a / b` and `c / d` (both in lowest terms), the former 

is simpler if `b < d` or if `b = d` and `|a| < |c|`. 

  

The effect of rounding modes is slightly counter-intuitive. 

Consider the case of round-toward-minus-infinity. This rounding is 

performed when coercing a rational to a floating-point number; so 

the :meth:`simplest_rational()` of a round-to-minus-infinity number 

will be either exactly equal to or slightly larger than the number. 

  

EXAMPLES:: 

  

sage: RRd = RealField(53, rnd='RNDD') 

sage: RRz = RealField(53, rnd='RNDZ') 

sage: RRu = RealField(53, rnd='RNDU') 

sage: RRa = RealField(53, rnd='RNDA') 

sage: def check(x): 

....: rx = x.simplest_rational() 

....: assert x == rx 

....: return rx 

sage: RRd(1/3) < RRu(1/3) 

True 

sage: check(RRd(1/3)) 

1/3 

sage: check(RRu(1/3)) 

1/3 

sage: check(RRz(1/3)) 

1/3 

sage: check(RRa(1/3)) 

1/3 

sage: check(RR(1/3)) 

1/3 

sage: check(RRd(-1/3)) 

-1/3 

sage: check(RRu(-1/3)) 

-1/3 

sage: check(RRz(-1/3)) 

-1/3 

sage: check(RRa(-1/3)) 

-1/3 

sage: check(RR(-1/3)) 

-1/3 

sage: check(RealField(20)(pi)) 

355/113 

sage: check(RR(pi)) 

245850922/78256779 

sage: check(RR(2).sqrt()) 

131836323/93222358 

sage: check(RR(1/2^210)) 

1/1645504557321205859467264516194506011931735427766374553794641921 

sage: check(RR(2^210)) 

1645504557321205950811116849375918117252433820865891134852825088 

sage: (RR(17).sqrt()).simplest_rational()^2 - 17 

-1/348729667233025 

sage: (RR(23).cube_root()).simplest_rational()^3 - 23 

-1404915133/264743395842039084891584 

sage: RRd5 = RealField(5, rnd='RNDD') 

sage: RRu5 = RealField(5, rnd='RNDU') 

sage: RR5 = RealField(5) 

sage: below1 = RR5(1).nextbelow() 

sage: check(RRd5(below1)) 

31/32 

sage: check(RRu5(below1)) 

16/17 

sage: check(below1) 

21/22 

sage: below1.exact_rational() 

31/32 

sage: above1 = RR5(1).nextabove() 

sage: check(RRd5(above1)) 

10/9 

sage: check(RRu5(above1)) 

17/16 

sage: check(above1) 

12/11 

sage: above1.exact_rational() 

17/16 

sage: check(RR(1234)) 

1234 

sage: check(RR5(1234)) 

1185 

sage: check(RR5(1184)) 

1120 

sage: RRd2 = RealField(2, rnd='RNDD') 

sage: RRu2 = RealField(2, rnd='RNDU') 

sage: RR2 = RealField(2) 

sage: check(RR2(8)) 

7 

sage: check(RRd2(8)) 

8 

sage: check(RRu2(8)) 

7 

sage: check(RR2(13)) 

11 

sage: check(RRd2(13)) 

12 

sage: check(RRu2(13)) 

13 

sage: check(RR2(16)) 

14 

sage: check(RRd2(16)) 

16 

sage: check(RRu2(16)) 

13 

sage: check(RR2(24)) 

21 

sage: check(RRu2(24)) 

17 

sage: check(RR2(-24)) 

-21 

sage: check(RRu2(-24)) 

-24 

  

TESTS:: 

  

sage: RR('nan').simplest_rational() 

Traceback (most recent call last): 

... 

ValueError: Cannot convert NaN or infinity to rational number 

sage: RR('-infinity').simplest_rational() 

Traceback (most recent call last): 

... 

ValueError: Cannot convert NaN or infinity to rational number 

""" 

if not mpfr_number_p(self.value): 

raise ValueError('Cannot convert NaN or infinity to rational number') 

  

if mpfr_zero_p(self.value): 

return Rational(0) 

  

from .real_mpfi import RealIntervalField 

  

cdef mpfr_rnd_t rnd = (<RealField_class>self._parent).rnd 

cdef int prec = (<RealField_class>self._parent).__prec 

  

cdef RealNumber low, high 

cdef int odd 

  

if rnd == MPFR_RNDN: 

# hp == "high precision" 

hp_field = RealField(prec + 1) 

hp_val = hp_field(self) 

hp_intv_field = RealIntervalField(prec + 1) 

low = hp_val.nextbelow() 

high = hp_val.nextabove() 

hp_intv = hp_intv_field(low, high) 

# In MPFR_RNDN mode, we round to nearest, preferring even mantissas 

# if we are exactly halfway between representable floats. 

# Thus, the values low and high will round to self iff the 

# mantissa of self is even. (Note that this only matters 

# if low or high is an integer; if they are not integers, 

# then self is simpler than either low or high.) 

# Is there a better (faster) way to check this? 

odd = self._parent(low) != self 

return hp_intv.simplest_rational(low_open=odd, high_open=odd) 

  

if rnd == MPFR_RNDZ: 

if mpfr_sgn(self.value) > 0: 

rnd = MPFR_RNDD 

else: 

rnd = MPFR_RNDU 

elif rnd == MPFR_RNDA: 

if mpfr_sgn(self.value) > 0: 

rnd = MPFR_RNDU 

else: 

rnd = MPFR_RNDD 

  

intv_field = RealIntervalField(prec) 

  

if rnd == MPFR_RNDD: 

intv = intv_field(self, self.nextabove()) 

return intv.simplest_rational(high_open = True) 

if rnd == MPFR_RNDU: 

intv = intv_field(self.nextbelow(), self) 

return intv.simplest_rational(low_open = True) 

  

def nearby_rational(self, max_error=None, max_denominator=None): 

""" 

Find a rational near to ``self``. Exactly one of ``max_error`` or 

``max_denominator`` must be specified. 

  

If ``max_error`` is specified, then this returns the simplest rational 

in the range ``[self-max_error .. self+max_error]``. If 

``max_denominator`` is specified, then this returns the rational 

closest to ``self`` with denominator at most ``max_denominator``. 

(In case of ties, we pick the simpler rational.) 

  

EXAMPLES:: 

  

sage: (0.333).nearby_rational(max_error=0.001) 

1/3 

sage: (0.333).nearby_rational(max_error=1) 

0 

sage: (-0.333).nearby_rational(max_error=0.0001) 

-257/772 

  

:: 

  

sage: (0.333).nearby_rational(max_denominator=100) 

1/3 

sage: RR(1/3 + 1/1000000).nearby_rational(max_denominator=2999999) 

777780/2333333 

sage: RR(1/3 + 1/1000000).nearby_rational(max_denominator=3000000) 

1000003/3000000 

sage: (-0.333).nearby_rational(max_denominator=1000) 

-333/1000 

sage: RR(3/4).nearby_rational(max_denominator=2) 

1 

sage: RR(pi).nearby_rational(max_denominator=120) 

355/113 

sage: RR(pi).nearby_rational(max_denominator=10000) 

355/113 

sage: RR(pi).nearby_rational(max_denominator=100000) 

312689/99532 

sage: RR(pi).nearby_rational(max_denominator=1) 

3 

sage: RR(-3.5).nearby_rational(max_denominator=1) 

-3 

  

TESTS:: 

  

sage: RR('nan').nearby_rational(max_denominator=1000) 

Traceback (most recent call last): 

... 

ValueError: Cannot convert NaN or infinity to rational number 

sage: RR('nan').nearby_rational(max_error=0.01) 

Traceback (most recent call last): 

... 

ValueError: Cannot convert NaN or infinity to rational number 

sage: RR(oo).nearby_rational(max_denominator=1000) 

Traceback (most recent call last): 

... 

ValueError: Cannot convert NaN or infinity to rational number 

sage: RR(oo).nearby_rational(max_error=0.01) 

Traceback (most recent call last): 

... 

ValueError: Cannot convert NaN or infinity to rational number 

""" 

  

if not mpfr_number_p(self.value): 

raise ValueError('Cannot convert NaN or infinity to rational number') 

  

if ((max_error is None and max_denominator is None) or 

(max_error is not None and max_denominator is not None)): 

raise ValueError('Must specify exactly one of max_error or max_denominator in nearby_rational()') 

  

if max_error is not None: 

from .real_mpfi import RealIntervalField 

  

intv_field = RealIntervalField(self.prec()) 

intv = intv_field(self - max_error, self + max_error) 

  

return intv.simplest_rational() 

  

cdef int sgn = mpfr_sgn(self.value) 

  

if sgn == 0: 

return Rational(0) 

  

cdef Rational self_r = self.exact_rational() 

  

cdef Integer self_d = self_r.denominator() 

  

if self_d <= max_denominator: 

return self_r 

  

if sgn < 0: 

self_r = -self_r 

  

cdef Integer fl = self_r.floor() 

cdef Rational target = self_r - fl 

  

cdef int low_done = 0 

cdef int high_done = 0 

  

# We use the Stern-Brocot tree to find the nearest neighbors of 

# self with denominator at most max_denominator. However, 

# navigating the Stern-Brocot tree in the straightforward way 

# can be very slow; for instance, to get to 1/1000000 takes a 

# million steps. Instead, we perform many steps at once; 

# this probably slows down the average case, but it drastically 

# speeds up the worst case. 

  

# Suppose we have a/b < c/d < e/f, where a/b and e/f are 

# neighbors in the Stern-Brocot tree and c/d is the target. 

# We alternate between moving the low and the high end toward 

# the target as much as possible. Suppose that there are 

# k consecutive rightward moves in the Stern-Brocot tree 

# traversal; then we end up with (a+k*e)/(b+k*f). We have 

# two constraints on k. First, the result must be <= c/d; 

# this gives us the following: 

# (a+k*e)/(b+k*f) <= c/d 

# d*a + k*(d*e) <= c*b + k*(c*f) 

# k*(d*e) - k*(c*f) <= c*b - d*a 

# k <= (c*b - d*a)/(d*e - c*f) 

# when moving the high side, we get 

# (k*a+e)/(k*b+f) >= c/d 

# k*(d*a) + d*e >= k*(c*b) + c*f 

# d*e - c*f >= k*(c*b - d*a) 

# k <= (d*e - c*f)/(c*b - d*a) 

  

# We also need the denominator to be <= max_denominator; this 

# gives (b+k*f) <= max_denominator or 

# k <= (max_denominator - b)/f 

# or 

# k <= (max_denominator - f)/b 

  

# We use variables with the same names as in the math above. 

  

cdef Integer a = Integer(0) 

cdef Integer b = Integer(1) 

cdef Integer c = target.numerator() 

cdef Integer d = target.denominator() 

cdef Integer e = Integer(1) 

cdef Integer f = Integer(1) 

  

cdef Integer k 

  

while (not low_done) or (not high_done): 

# Move the low side 

k = (c*b - d*a) // (d*e - c*f) 

  

if b+k*f > max_denominator: 

k = (max_denominator - b) // f 

low_done = True 

  

if k == 0: 

low_done = True 

  

a = a + k*e 

b = b + k*f 

  

# Move the high side 

k = (d*e - c*f) // (c*b - d*a) 

  

if k*b + f >= max_denominator: 

k = (max_denominator - f) // b 

high_done = True 

  

if k == 0: 

high_done = True 

  

e = k*a + e 

f = k*b + f 

  

# Now a/b and e/f are rationals surrounding c/d. We know that 

# neither is equal to c/d, since d > max_denominator and 

# b and f are both <= max_denominator. (We know that 

# d > max_denominator because we return early (before we 

# get here) if d <= max_denominator.) 

  

low = a / b 

high = e / f 

  

D0 = target - low 

D1 = high - target 

if D1 < D0: 

result = high 

elif D0 < D1: 

result = low 

else: 

if f < b: 

result = high 

elif b < f: 

result = low 

else: 

if e < a: 

result = high 

else: 

result = low 

  

result += fl 

  

if sgn < 0: 

return -result 

return result 

  

def __mpfr__(self): 

""" 

Convert Sage ``RealNumber`` to gmpy2 ``mpfr``. 

  

EXAMPLES:: 

  

sage: r = RR(4.12) 

sage: r.__mpfr__() # optional - gmpy2 

mpfr('4.1200000000000001') 

sage: from gmpy2 import mpfr # optional - gmpy2 

sage: mpfr(RR(4.5)) # optional - gmpy2 

mpfr('4.5') 

sage: R = RealField(127) 

sage: mpfr(R.pi()).precision # optional - gmpy2 

127 

sage: R = RealField(42) 

sage: mpfr(R.pi()).precision # optional - gmpy2 

42 

sage: R = RealField(256) 

sage: x = mpfr(R.pi()) # optional - gmpy2 

sage: x.precision # optional - gmpy2 

256 

sage: y = R(x) # optional - gmpy2 

sage: mpfr(y) == x # optional - gmpy2 

True 

sage: x = mpfr('2.567e42', precision=128) # optional - gmpy2 

sage: y = RealField(128)(x) # optional - gmpy2 

sage: mpfr(y) == x # optional - gmpy2 

True 

  

TESTS:: 

  

sage: r.__mpfr__(); raise NotImplementedError("gmpy2 is not installed") 

Traceback (most recent call last): 

... 

NotImplementedError: gmpy2 is not installed 

""" 

IF HAVE_GMPY2: 

return gmpy2.GMPy_MPFR_From_mpfr(self.value) 

ELSE: 

raise NotImplementedError("gmpy2 is not installed") 

  

########################################### 

# Comparisons: ==, !=, <, <=, >, >= 

########################################### 

  

def is_NaN(self): 

""" 

Return ``True`` if ``self`` is Not-a-Number ``NaN``. 

  

EXAMPLES:: 

  

sage: a = RR(0) / RR(0); a 

NaN 

sage: a.is_NaN() 

True 

""" 

return mpfr_nan_p(self.value) 

  

def is_positive_infinity(self): 

r""" 

Return ``True`` if ``self`` is `+\infty`. 

  

EXAMPLES:: 

  

sage: a = RR('1.494') / RR(0); a 

+infinity 

sage: a.is_positive_infinity() 

True 

sage: a = -RR('1.494') / RR(0); a 

-infinity 

sage: RR(1.5).is_positive_infinity() 

False 

sage: a.is_positive_infinity() 

False 

""" 

return mpfr_inf_p(self.value) and mpfr_sgn(self.value) > 0 

  

def is_negative_infinity(self): 

r""" 

Return ``True`` if ``self`` is `-\infty`. 

  

EXAMPLES:: 

  

sage: a = RR('1.494') / RR(0); a 

+infinity 

sage: a.is_negative_infinity() 

False 

sage: a = -RR('1.494') / RR(0); a 

-infinity 

sage: RR(1.5).is_negative_infinity() 

False 

sage: a.is_negative_infinity() 

True 

""" 

return mpfr_inf_p(self.value) and mpfr_sgn(self.value) < 0 

  

def is_infinity(self): 

""" 

Return ``True`` if ``self`` is `\infty` and ``False`` otherwise. 

  

EXAMPLES:: 

  

sage: a = RR('1.494') / RR(0); a 

+infinity 

sage: a.is_infinity() 

True 

sage: a = -RR('1.494') / RR(0); a 

-infinity 

sage: a.is_infinity() 

True 

sage: RR(1.5).is_infinity() 

False 

sage: RR('nan').is_infinity() 

False 

""" 

return mpfr_inf_p(self.value) 

  

def is_unit(self): 

""" 

Return ``True`` if ``self`` is a unit (has a multiplicative inverse) 

and ``False`` otherwise. 

  

EXAMPLES:: 

  

sage: RR(1).is_unit() 

True 

sage: RR('0').is_unit() 

False 

sage: RR('-0').is_unit() 

False 

sage: RR('nan').is_unit() 

False 

sage: RR('inf').is_unit() 

False 

sage: RR('-inf').is_unit() 

False 

""" 

return mpfr_sgn(self.value) != 0 and not mpfr_inf_p(self.value) 

  

def is_real(self): 

""" 

Return ``True`` if ``self`` is real (of course, this always returns 

``True`` for a finite element of a real field). 

  

EXAMPLES:: 

  

sage: RR(1).is_real() 

True 

sage: RR('-100').is_real() 

True 

sage: RR(NaN).is_real() 

False 

""" 

return not mpfr_nan_p(self.value) 

  

def is_integer(self): 

""" 

Return ``True`` if this number is a integer. 

  

EXAMPLES:: 

  

sage: RR(1).is_integer() 

True 

sage: RR(0.1).is_integer() 

False 

""" 

return mpfr_integer_p(self.value) != 0 

  

def __nonzero__(self): 

""" 

Return ``True`` if ``self`` is nonzero. 

  

EXAMPLES:: 

  

sage: bool(RR(1)) 

True 

sage: bool(RR(0)) 

False 

sage: bool(RR('inf')) 

True 

  

TESTS: 

  

Check that :trac:`20502` is fixed:: 

  

sage: bool(RR('nan')) 

True 

sage: RR('nan').is_zero() 

False 

""" 

return not mpfr_zero_p(self.value) 

  

cpdef _richcmp_(self, other, int op): 

""" 

Compare ``self`` and ``other`` according to the rich 

comparison operator ``op``. 

  

EXAMPLES:: 

  

sage: RR('-inf') < RR('inf') 

True 

sage: RR('-inf') < RR(-10000) 

True 

sage: RR(100000000) < RR('inf') 

True 

sage: RR(100000000) > RR('inf') 

False 

sage: RR(100000000) < RR('inf') 

True 

sage: RR(-1000) < RR(1000) 

True 

sage: RR(1) < RR(1).nextabove() 

True 

sage: RR(1) <= RR(1).nextabove() 

True 

sage: RR(1) <= RR(1) 

True 

sage: RR(1) < RR(1) 

False 

sage: RR(1) > RR(1) 

False 

sage: RR(1) >= RR(1) 

True 

sage: RR('inf') == RR('inf') 

True 

sage: RR('inf') == RR('-inf') 

False 

  

A ``NaN`` is not equal to anything, including itself:: 

  

sage: RR('nan') == RR('nan') 

False 

sage: RR('nan') != RR('nan') 

True 

sage: RR('nan') < RR('nan') 

False 

sage: RR('nan') > RR('nan') 

False 

sage: RR('nan') <= RR('nan') 

False 

sage: RR('nan') >= RR('nan') 

False 

sage: RR('nan') == RR(0) 

False 

sage: RR('nan') != RR(0) 

True 

sage: RR('nan') < RR(0) 

False 

sage: RR('nan') > RR(0) 

False 

sage: RR('nan') <= RR(0) 

False 

sage: RR('nan') >= RR(0) 

False 

""" 

cdef RealNumber y = <RealNumber>other 

if mpfr_nan_p(self.value) or mpfr_nan_p(y.value): 

return op == Py_NE 

cdef int c = mpfr_cmp(self.value, y.value) 

return rich_to_bool_sgn(op, c) 

  

############################ 

# Special Functions 

############################ 

  

def sqrt(self, extend=True, all=False): 

r""" 

The square root function. 

  

INPUT: 

  

- ``extend`` -- bool (default: ``True``); if ``True``, return a 

square root in a complex field if necessary if ``self`` is negative; 

otherwise raise a ``ValueError`` 

  

- ``all`` -- bool (default: ``False``); if ``True``, return a 

list of all square roots. 

  

EXAMPLES:: 

  

sage: r = -2.0 

sage: r.sqrt() 

1.41421356237310*I 

  

:: 

  

sage: r = 4.0 

sage: r.sqrt() 

2.00000000000000 

sage: r.sqrt()^2 == r 

True 

  

:: 

  

sage: r = 4344 

sage: r.sqrt() 

2*sqrt(1086) 

  

:: 

  

sage: r = 4344.0 

sage: r.sqrt()^2 == r 

True 

sage: r.sqrt()^2 - r 

0.000000000000000 

  

:: 

  

sage: r = -2.0 

sage: r.sqrt() 

1.41421356237310*I 

""" 

cdef RealNumber x 

if mpfr_cmp_ui(self.value, 0) >= 0: 

x = self._new() 

if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_on() 

mpfr_sqrt(x.value, self.value, (<RealField_class>self._parent).rnd) 

if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_off() 

if all: 

if x.is_zero(): 

return [x] 

else: 

return [x, -x] 

return x 

if not extend: 

raise ValueError("negative number %s does not have a square root in the real field" % self) 

return self._complex_number_().sqrt(all=all) 

  

def is_square(self): 

""" 

Return whether or not this number is a square in this field. For 

the real numbers, this is ``True`` if and only if ``self`` is 

non-negative. 

  

EXAMPLES:: 

  

sage: r = 3.5 

sage: r.is_square() 

True 

sage: r = 0.0 

sage: r.is_square() 

True 

sage: r = -4.0 

sage: r.is_square() 

False 

""" 

return mpfr_sgn(self.value) >= 0 

  

def cube_root(self): 

""" 

Return the cubic root (defined over the real numbers) of ``self``. 

  

EXAMPLES:: 

  

sage: r = 125.0; r.cube_root() 

5.00000000000000 

sage: r = -119.0 

sage: r.cube_root()^3 - r # illustrates precision loss 

-1.42108547152020e-14 

""" 

cdef RealNumber x = self._new() 

if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_on() 

mpfr_cbrt(x.value, self.value, (<RealField_class>self._parent).rnd) 

if (<RealField_class>self._parent).__prec > 10*SIG_PREC_THRESHOLD: sig_off() 

return x 

  

def __pow(self, RealNumber exponent): 

""" 

Compute ``self`` raised to the power of exponent, rounded in the 

direction specified by the parent of ``self``. 

  

EXAMPLES:: 

  

sage: R = RealField(30) 

sage: a = R('1.23456') 

sage: a.__pow(20.0) 

67.646297 

""" 

cdef RealNumber x 

x = self._new() 

sig_on() 

mpfr_pow(x.value, self.value, exponent.value, (<RealField_class>self._parent).rnd) 

sig_off() 

if mpfr_nan_p(x.value): 

return self._complex_number_()**exponent._complex_number_() 

return x 

  

def __pow__(self, exponent, modulus): 

""" 

Compute ``self`` raised to the power of exponent, rounded in the 

direction specified by the parent of ``self``. 

  

If the result is not a real number, ``self`` and the exponent are both 

coerced to complex numbers (with sufficient precision), then the 

exponentiation is computed in the complex numbers. Thus this 

function can return either a real or complex number. 

  

EXAMPLES:: 

  

sage: R = RealField(30) 

sage: a = R('1.23456') 

sage: a^20 

67.646297 

sage: a^a 

1.2971115 

sage: b = R(-1) 

sage: b^(1/2) 

-8.7055157e-10 + 1.0000000*I 

  

We raise a real number to a symbolic object:: 

  

sage: x, y = var('x,y') 

sage: 1.5^x 

1.50000000000000^x 

sage: -2.3^(x+y^3+sin(x)) 

-2.30000000000000^(y^3 + x + sin(x)) 

  

TESTS: 

  

We see that :trac:`10736` is fixed:: 

  

sage: 16^0.5 

4.00000000000000 

sage: int(16)^0.5 

4.00000000000000 

sage: (1/2)^2.0 

0.250000000000000 

sage: [n^(1.5) for n in range(10)] 

[0.000000000000000, 1.00000000000000, 2.82842712474619, 5.19615242270663, 8.00000000000000, 11.1803398874989, 14.6969384566991, 18.5202591774521, 22.6274169979695, 27.0000000000000] 

sage: int(-2)^(0.333333) 

0.629961522017056 + 1.09112272417509*I 

sage: int(0)^(1.0) 

0.000000000000000 

sage: int(0)^(0.0) 

1.00000000000000 

""" 

cdef RealNumber base, x 

cdef mpfr_rnd_t rounding_mode 

if isinstance(self, RealNumber): 

base = <RealNumber>self 

rounding_mode = (<RealField_class>base._parent).rnd 

x = base._new() 

sig_on() 

if isinstance(exponent, int): 

mpfr_pow_si(x.value, base.value, exponent, rounding_mode) 

elif isinstance(exponent, Integer): 

mpfr_pow_z(x.value, base.value, (<Integer>exponent).value, rounding_mode) 

elif isinstance(exponent, RealNumber): 

mpfr_pow(x.value, base.value, (<RealNumber>exponent).value, rounding_mode) 

else: 

sig_off() 

return bin_op(self, exponent, operator.pow) 

sig_off() 

if mpfr_nan_p(x.value): 

return base._complex_number_() ** exponent 

return x 

else: 

return bin_op(self, exponent, operator.pow) 

  

def log(self, base=None): 

""" 

Return the logarithm of ``self`` to the ``base``. 

  

EXAMPLES:: 

  

sage: R = RealField() 

sage: R(2).log() 

0.693147180559945 

sage: log(RR(2)) 

0.693147180559945 

sage: log(RR(2), "e") 

0.693147180559945 

sage: log(RR(2), e) 

0.693147180559945 

  

:: 

  

sage: r = R(-1); r.log() 

3.14159265358979*I 

sage: log(RR(-1),e) 

3.14159265358979*I 

sage: r.log(2) 

4.53236014182719*I 

  

For the error value NaN (Not A Number), log will return NaN:: 

  

sage: r = R(NaN); r.log() 

NaN 

  

""" 

if mpfr_nan_p(self.value): 

return self 

  

cdef RealNumber x 

if self < 0: 

if base is None or base == 'e': 

return self._complex_number_().log() 

else: 

return self._complex_number_().log(base) 

if base is None or base == 'e': 

x = self._new() 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on() 

mpfr_log(x.value, self.value, (<RealField_class>self._parent).rnd) 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off() 

return x 

elif base == 10: 

return self.log10() 

elif base == 2: 

return self.log2() 

else: 

return self.log() / (self.parent()(base)).log() 

  

def log2(self): 

""" 

Return log to the base 2 of ``self``. 

  

EXAMPLES:: 

  

sage: r = 16.0 

sage: r.log2() 

4.00000000000000 

  

:: 

  

sage: r = 31.9; r.log2() 

4.99548451887751 

  

:: 

  

sage: r = 0.0 

sage: r.log2() 

-infinity 

  

:: 

  

sage: r = -3.0; r.log2() 

1.58496250072116 + 4.53236014182719*I 

""" 

cdef RealNumber x 

if self < 0: 

return self._complex_number_().log(2) 

x = self._new() 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on() 

mpfr_log2(x.value, self.value, (<RealField_class>self._parent).rnd) 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off() 

return x 

  

def log10(self): 

""" 

Return log to the base 10 of ``self``. 

  

EXAMPLES:: 

  

sage: r = 16.0; r.log10() 

1.20411998265592 

sage: r.log() / log(10.0) 

1.20411998265592 

  

:: 

  

sage: r = 39.9; r.log10() 

1.60097289568675 

  

:: 

  

sage: r = 0.0 

sage: r.log10() 

-infinity 

  

:: 

  

sage: r = -1.0 

sage: r.log10() 

1.36437635384184*I 

""" 

cdef RealNumber x 

if self < 0: 

return self._complex_number_().log(10) 

x = self._new() 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on() 

mpfr_log10(x.value, self.value, (<RealField_class>self._parent).rnd) 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off() 

return x 

  

def log1p(self): 

""" 

Return log base `e` of ``1 + self``. 

  

EXAMPLES:: 

  

sage: r = 15.0; r.log1p() 

2.77258872223978 

sage: (r+1).log() 

2.77258872223978 

  

For small values, this is more accurate than computing 

``log(1 + self)`` directly, as it avoids cancellation issues:: 

  

sage: r = 3e-10 

sage: r.log1p() 

2.99999999955000e-10 

sage: (1+r).log() 

3.00000024777111e-10 

sage: r100 = RealField(100)(r) 

sage: (1+r100).log() 

2.9999999995500000000978021372e-10 

  

:: 

  

sage: r = 38.9; r.log1p() 

3.68637632389582 

  

:: 

  

sage: r = -1.0 

sage: r.log1p() 

-infinity 

  

:: 

  

sage: r = -2.0 

sage: r.log1p() 

3.14159265358979*I 

""" 

cdef RealNumber x 

if self < -1: 

return (self+1.0)._complex_number_().log() 

x = self._new() 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on() 

mpfr_log1p(x.value, self.value, (<RealField_class>self._parent).rnd) 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off() 

return x 

  

def exp(self): 

r""" 

Return `e^\mathtt{self}`. 

  

EXAMPLES:: 

  

sage: r = 0.0 

sage: r.exp() 

1.00000000000000 

  

:: 

  

sage: r = 32.3 

sage: a = r.exp(); a 

1.06588847274864e14 

sage: a.log() 

32.3000000000000 

  

:: 

  

sage: r = -32.3 

sage: r.exp() 

9.38184458849869e-15 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_exp(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def exp2(self): 

r""" 

Return `2^\mathtt{self}`. 

  

EXAMPLES:: 

  

sage: r = 0.0 

sage: r.exp2() 

1.00000000000000 

  

:: 

  

sage: r = 32.0 

sage: r.exp2() 

4.29496729600000e9 

  

:: 

  

sage: r = -32.3 

sage: r.exp2() 

1.89117248253021e-10 

""" 

cdef RealNumber x = self._new() 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on() 

mpfr_exp2(x.value, self.value, (<RealField_class>self._parent).rnd) 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off() 

return x 

  

def exp10(self): 

r""" 

Return `10^\mathtt{self}`. 

  

EXAMPLES:: 

  

sage: r = 0.0 

sage: r.exp10() 

1.00000000000000 

  

:: 

  

sage: r = 32.0 

sage: r.exp10() 

1.00000000000000e32 

  

:: 

  

sage: r = -32.3 

sage: r.exp10() 

5.01187233627276e-33 

""" 

cdef RealNumber x = self._new() 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on() 

mpfr_exp10(x.value, self.value, (<RealField_class>self._parent).rnd) 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off() 

return x 

  

def expm1(self): 

r""" 

Return `e^\mathtt{self}-1`, avoiding cancellation near 0. 

  

EXAMPLES:: 

  

sage: r = 1.0 

sage: r.expm1() 

1.71828182845905 

  

:: 

  

sage: r = 1e-16 

sage: exp(r)-1 

0.000000000000000 

sage: r.expm1() 

1.00000000000000e-16 

""" 

cdef RealNumber x = self._new() 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on() 

mpfr_expm1(x.value, self.value, (<RealField_class>self._parent).rnd) 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off() 

return x 

  

def eint(self): 

""" 

Returns the exponential integral of this number. 

  

EXAMPLES:: 

  

sage: r = 1.0 

sage: r.eint() 

1.89511781635594 

  

:: 

  

sage: r = -1.0 

sage: r.eint() 

-0.219383934395520 

""" 

cdef RealNumber x = self._new() 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on() 

mpfr_eint(x.value, self.value, (<RealField_class>self._parent).rnd) 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on() 

return x 

  

def cos(self): 

""" 

Returnn the cosine of ``self``. 

  

EXAMPLES:: 

  

sage: t=RR.pi()/2 

sage: t.cos() 

6.12323399573677e-17 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_cos(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def sin(self): 

""" 

Return the sine of ``self``. 

  

EXAMPLES:: 

  

sage: R = RealField(100) 

sage: R(2).sin() 

0.90929742682568169539601986591 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_sin(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def tan(self): 

""" 

Return the tangent of ``self``. 

  

EXAMPLES:: 

  

sage: q = RR.pi()/3 

sage: q.tan() 

1.73205080756888 

sage: q = RR.pi()/6 

sage: q.tan() 

0.577350269189626 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_tan(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def sincos(self): 

""" 

Return a pair consisting of the sine and cosine of ``self``. 

  

EXAMPLES:: 

  

sage: R = RealField() 

sage: t = R.pi()/6 

sage: t.sincos() 

(0.500000000000000, 0.866025403784439) 

""" 

cdef RealNumber x,y 

x = self._new() 

y = self._new() 

sig_on() 

mpfr_sin_cos(x.value, y.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x,y 

  

def arccos(self): 

""" 

Return the inverse cosine of ``self``. 

  

EXAMPLES:: 

  

sage: q = RR.pi()/3 

sage: i = q.cos() 

sage: i.arccos() == q 

True 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_acos(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def arcsin(self): 

""" 

Return the inverse sine of ``self``. 

  

EXAMPLES:: 

  

sage: q = RR.pi()/5 

sage: i = q.sin() 

sage: i.arcsin() == q 

True 

sage: i.arcsin() - q 

0.000000000000000 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_asin(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def arctan(self): 

""" 

Return the inverse tangent of ``self``. 

  

EXAMPLES:: 

  

sage: q = RR.pi()/5 

sage: i = q.tan() 

sage: i.arctan() == q 

True 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_atan(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def cosh(self): 

""" 

Return the hyperbolic cosine of ``self``. 

  

EXAMPLES:: 

  

sage: q = RR.pi()/12 

sage: q.cosh() 

1.03446564009551 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_cosh(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def sinh(self): 

""" 

Return the hyperbolic sine of ``self``. 

  

EXAMPLES:: 

  

sage: q = RR.pi()/12 

sage: q.sinh() 

0.264800227602271 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_sinh(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def tanh(self): 

""" 

Return the hyperbolic tangent of ``self``. 

  

EXAMPLES:: 

  

sage: q = RR.pi()/11 

sage: q.tanh() 

0.278079429295850 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_tanh(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def coth(self): 

""" 

Return the hyperbolic cotangent of ``self``. 

  

EXAMPLES:: 

  

sage: RealField(100)(2).coth() 

1.0373147207275480958778097648 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_coth(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def arccoth(self): 

""" 

Return the inverse hyperbolic cotangent of ``self``. 

  

EXAMPLES:: 

  

sage: q = RR.pi()/5 

sage: i = q.coth() 

sage: i.arccoth() == q 

True 

""" 

return (~self).arctanh() 

  

def cot(self): 

""" 

Return the cotangent of ``self``. 

  

EXAMPLES:: 

  

sage: RealField(100)(2).cot() 

-0.45765755436028576375027741043 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_cot(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def csch(self): 

""" 

Return the hyperbolic cosecant of ``self``. 

  

EXAMPLES:: 

  

sage: RealField(100)(2).csch() 

0.27572056477178320775835148216 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_csch(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def arccsch(self): 

""" 

Return the inverse hyperbolic cosecant of ``self``. 

  

EXAMPLES:: 

  

sage: i = RR.pi()/5 

sage: q = i.csch() 

sage: q.arccsch() == i 

True 

""" 

return (~self).arcsinh() 

  

def csc(self): 

""" 

Return the cosecant of ``self``. 

  

EXAMPLES:: 

  

sage: RealField(100)(2).csc() 

1.0997501702946164667566973970 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_csc(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def sech(self): 

""" 

Return the hyperbolic secant of ``self``. 

  

EXAMPLES:: 

  

sage: RealField(100)(2).sech() 

0.26580222883407969212086273982 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_sech(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def arcsech(self): 

""" 

Return the inverse hyperbolic secant of ``self``. 

  

EXAMPLES:: 

  

sage: i = RR.pi()/3 

sage: q = i.sech() 

sage: q.arcsech() == i 

True 

""" 

return (~self).arccosh() 

  

def sec(self): 

""" 

Returns the secant of this number 

  

EXAMPLES:: 

  

sage: RealField(100)(2).sec() 

-2.4029979617223809897546004014 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_sec(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def arccosh(self): 

""" 

Return the hyperbolic inverse cosine of ``self``. 

  

EXAMPLES:: 

  

sage: q = RR.pi()/2 

sage: i = q.cosh() ; i 

2.50917847865806 

sage: q == i.arccosh() 

True 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_acosh(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def arcsinh(self): 

""" 

Return the hyperbolic inverse sine of ``self``. 

  

EXAMPLES:: 

  

sage: q = RR.pi()/7 

sage: i = q.sinh() ; i 

0.464017630492991 

sage: i.arcsinh() - q 

0.000000000000000 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_asinh(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def arctanh(self): 

""" 

Return the hyperbolic inverse tangent of ``self``. 

  

EXAMPLES:: 

  

sage: q = RR.pi()/7 

sage: i = q.tanh() ; i 

0.420911241048535 

sage: i.arctanh() - q 

0.000000000000000 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_atanh(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def agm(self, other): 

r""" 

Return the arithmetic-geometric mean of ``self`` and ``other``. 

  

The arithmetic-geometric mean is the common limit of the sequences 

`u_n` and `v_n`, where `u_0` is ``self``, 

`v_0` is other, `u_{n+1}` is the arithmetic mean 

of `u_n` and `v_n`, and `v_{n+1}` is the 

geometric mean of `u_n` and `v_n`. If any operand is negative, the 

return value is ``NaN``. 

  

INPUT: 

  

- ``right`` -- another real number 

  

OUTPUT: 

  

- the AGM of ``self`` and ``other`` 

  

EXAMPLES:: 

  

sage: a = 1.5 

sage: b = 2.5 

sage: a.agm(b) 

1.96811775182478 

sage: RealField(200)(a).agm(b) 

1.9681177518247777389894630877503739489139488203685819712291 

sage: a.agm(100) 

28.1189391225320 

  

The AGM always lies between the geometric and arithmetic mean:: 

  

sage: sqrt(a*b) < a.agm(b) < (a+b)/2 

True 

  

It is, of course, symmetric:: 

  

sage: b.agm(a) 

1.96811775182478 

  

and satisfies the relation `AGM(ra, rb) = r AGM(a, b)`:: 

  

sage: (2*a).agm(2*b) / 2 

1.96811775182478 

sage: (3*a).agm(3*b) / 3 

1.96811775182478 

  

It is also related to the elliptic integral 

  

.. MATH:: 

  

\int_0^{\pi/2} \frac{d\theta}{\sqrt{1-m\sin^2\theta}}. 

  

:: 

  

sage: m = (a-b)^2/(a+b)^2 

sage: E = numerical_integral(1/sqrt(1-m*sin(x)^2), 0, RR.pi()/2)[0] 

sage: RR.pi()/4 * (a+b)/E 

1.96811775182478 

  

TESTS:: 

  

sage: 1.5.agm(0) 

0.000000000000000 

""" 

cdef RealNumber x, _other 

if isinstance(other, RealNumber) and ((<Element>other)._parent is self._parent): 

_other = <RealNumber>other 

else: 

_other = self._parent(other) 

  

x = self._new() 

if (<RealField_class>self._parent).__prec > 10000: sig_on() 

mpfr_agm(x.value, self.value, _other.value, (<RealField_class>self._parent).rnd) 

if (<RealField_class>self._parent).__prec > 10000: sig_off() 

return x 

  

def erf(self): 

""" 

Return the value of the error function on ``self``. 

  

EXAMPLES:: 

  

sage: R = RealField(53) 

sage: R(2).erf() 

0.995322265018953 

sage: R(6).erf() 

1.00000000000000 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_erf(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def erfc(self): 

r""" 

Return the value of the complementary error function on ``self``, 

i.e., `1-\mathtt{erf}(\mathtt{self})`. 

  

EXAMPLES:: 

  

sage: R = RealField(53) 

sage: R(2).erfc() 

0.00467773498104727 

sage: R(6).erfc() 

2.15197367124989e-17 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_erfc(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def j0(self): 

""" 

Return the value of the Bessel `J` function of order 0 at ``self``. 

  

EXAMPLES:: 

  

sage: R = RealField(53) 

sage: R(2).j0() 

0.223890779141236 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_j0(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def j1(self): 

""" 

Return the value of the Bessel `J` function of order 1 at ``self``. 

  

EXAMPLES:: 

  

sage: R = RealField(53) 

sage: R(2).j1() 

0.576724807756873 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_j1(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def jn(self, long n): 

""" 

Return the value of the Bessel `J` function of order `n` at ``self``. 

  

EXAMPLES:: 

  

sage: R = RealField(53) 

sage: R(2).jn(3) 

0.128943249474402 

sage: R(2).jn(-17) 

-2.65930780516787e-15 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_jn(x.value, n, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def y0(self): 

""" 

Return the value of the Bessel `Y` function of order 0 at ``self``. 

  

EXAMPLES:: 

  

sage: R = RealField(53) 

sage: R(2).y0() 

0.510375672649745 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_y0(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def y1(self): 

""" 

Return the value of the Bessel `Y` function of order 1 at ``self``. 

  

EXAMPLES:: 

  

sage: R = RealField(53) 

sage: R(2).y1() 

-0.107032431540938 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_y1(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def yn(self, long n): 

""" 

Return the value of the Bessel `Y` function of order `n` at ``self``. 

  

EXAMPLES:: 

  

sage: R = RealField(53) 

sage: R(2).yn(3) 

-1.12778377684043 

sage: R(2).yn(-17) 

7.09038821729481e12 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_yn(x.value, n, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def gamma(self): 

""" 

Return the value of the Euler gamma function on ``self``. 

  

EXAMPLES:: 

  

sage: R = RealField() 

sage: R(6).gamma() 

120.000000000000 

sage: R(1.5).gamma() 

0.886226925452758 

""" 

cdef RealNumber x = self._new() 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_on() 

mpfr_gamma(x.value, self.value, (<RealField_class>self._parent).rnd) 

if (<RealField_class>self._parent).__prec > SIG_PREC_THRESHOLD: sig_off() 

return x 

  

def log_gamma(self): 

""" 

Return the principal branch of the log gamma of ``self``. Note that 

this is not in general equal to log(gamma(``self``)) for negative 

input. 

  

EXAMPLES:: 

  

sage: R = RealField(53) 

sage: R(6).log_gamma() 

4.78749174278205 

sage: R(1e10).log_gamma() 

2.20258509288811e11 

sage: log_gamma(-2.1) 

1.53171380819509 - 9.42477796076938*I 

sage: log(gamma(-1.1)) == log_gamma(-1.1) 

False 

""" 

cdef RealNumber x = self._new() 

parent = (<RealField_class>self._parent) 

if not mpfr_sgn(self.value) < 0: 

if parent.__prec > SIG_PREC_THRESHOLD: 

sig_on() 

mpfr_lngamma(x.value, self.value, parent.rnd) 

if parent.__prec > SIG_PREC_THRESHOLD: 

sig_off() 

return x 

from sage.libs.mpmath.utils import call 

from mpmath import loggamma 

return call(loggamma, mpfr_to_mpfval(self.value), parent=parent) 

  

def zeta(self): 

r""" 

Return the Riemann zeta function evaluated at this real number 

  

.. NOTE:: 

  

PARI is vastly more efficient at computing the Riemann zeta 

function. See the example below for how to use it. 

  

EXAMPLES:: 

  

sage: R = RealField() 

sage: R(2).zeta() 

1.64493406684823 

sage: R.pi()^2/6 

1.64493406684823 

sage: R(-2).zeta() 

0.000000000000000 

sage: R(1).zeta() 

+infinity 

  

Computing zeta using PARI is much more efficient in difficult 

cases. Here's how to compute zeta with at least a given precision:: 

  

sage: z = pari(2).zeta(precision=53); z 

1.64493406684823 

sage: pari(2).zeta(precision=128).sage().prec() 

128 

sage: pari(2).zeta(precision=65).sage().prec() 

128 # 64-bit 

96 # 32-bit 

  

Note that the number of bits of precision in the constructor only 

effects the internal precision of the pari number, which is rounded 

up to the nearest multiple of 32 or 64. To increase the number of 

digits that gets displayed you must use 

``pari.set_real_precision``. 

  

:: 

  

sage: type(z) 

<type 'cypari2.gen.Gen'> 

sage: R(z) 

1.64493406684823 

""" 

cdef RealNumber x = self._new() 

sig_on() 

mpfr_zeta(x.value, self.value, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

def algebraic_dependency(self, n): 

""" 

Return a polynomial of degree at most `n` which is 

approximately satisfied by this number. 

  

.. NOTE:: 

  

The resulting polynomial need not be irreducible, and indeed 

usually won't be if this number is a good approximation to an 

algebraic number of degree less than `n`. 

  

ALGORITHM: 

  

Uses the PARI C-library ``algdep`` command. 

  

EXAMPLES:: 

  

sage: r = sqrt(2.0); r 

1.41421356237310 

sage: r.algebraic_dependency(5) 

x^2 - 2 

""" 

return sage.arith.all.algdep(self,n) 

  

algdep = algebraic_dependency 

  

def nth_root(self, int n, int algorithm=0): 

r""" 

Return an `n^{th}` root of ``self``. 

  

INPUT: 

  

- ``n`` -- A positive number, rounded down to the 

nearest integer. Note that `n` should be less than 

```sys.maxsize```. 

  

- ``algorithm`` -- Set this to 1 to call mpfr directly, 

set this to 2 to use interval arithmetic and logarithms, or leave 

it at the default of 0 to choose the algorithm which is estimated 

to be faster. 

  

AUTHORS: 

  

- Carl Witty (2007-10) 

  

EXAMPLES:: 

  

sage: R = RealField() 

sage: R(8).nth_root(3) 

2.00000000000000 

sage: R(8).nth_root(3.7) # illustrate rounding down 

2.00000000000000 

sage: R(-8).nth_root(3) 

-2.00000000000000 

sage: R(0).nth_root(3) 

0.000000000000000 

sage: R(32).nth_root(-1) 

Traceback (most recent call last): 

... 

ValueError: n must be positive 

sage: R(32).nth_root(1.0) 

32.0000000000000 

sage: R(4).nth_root(4) 

1.41421356237310 

sage: R(4).nth_root(40) 

1.03526492384138 

sage: R(4).nth_root(400) 

1.00347174850950 

sage: R(4).nth_root(4000) 

1.00034663365385 

sage: R(4).nth_root(4000000) 

1.00000034657365 

sage: R(-27).nth_root(3) 

-3.00000000000000 

sage: R(-4).nth_root(3999999) 

-1.00000034657374 

  

Note that for negative numbers, any even root throws an exception:: 

  

sage: R(-2).nth_root(6) 

Traceback (most recent call last): 

... 

ValueError: taking an even root of a negative number 

  

The `n^{th}` root of 0 is defined to be 0, for any `n`:: 

  

sage: R(0).nth_root(6) 

0.000000000000000 

sage: R(0).nth_root(7) 

0.000000000000000 

  

TESTS: 

  

The old and new algorithms should give exactly the same results in 

all cases:: 

  

sage: def check(x, n): 

....: answers = [] 

....: for sign in (1, -1): 

....: if is_even(n) and sign == -1: 

....: continue 

....: for rounding in ('RNDN', 'RNDD', 'RNDU', 'RNDZ'): 

....: fld = RealField(x.prec(), rnd=rounding) 

....: fx = fld(sign * x) 

....: alg_mpfr = fx.nth_root(n, algorithm=1) 

....: alg_mpfi = fx.nth_root(n, algorithm=2) 

....: assert(alg_mpfr == alg_mpfi) 

....: if sign == 1: answers.append(alg_mpfr) 

....: return answers 

  

Check some perfect powers (and nearby numbers):: 

  

sage: check(16.0, 4) 

[2.00000000000000, 2.00000000000000, 2.00000000000000, 2.00000000000000] 

sage: check((16.0).nextabove(), 4) 

[2.00000000000000, 2.00000000000000, 2.00000000000001, 2.00000000000000] 

sage: check((16.0).nextbelow(), 4) 

[2.00000000000000, 1.99999999999999, 2.00000000000000, 1.99999999999999] 

sage: check(((9.0 * 256)^7), 7) 

[2304.00000000000, 2304.00000000000, 2304.00000000000, 2304.00000000000] 

sage: check(((9.0 * 256)^7).nextabove(), 7) 

[2304.00000000000, 2304.00000000000, 2304.00000000001, 2304.00000000000] 

sage: check(((9.0 * 256)^7).nextbelow(), 7) 

[2304.00000000000, 2303.99999999999, 2304.00000000000, 2303.99999999999] 

sage: check(((5.0 / 512)^17), 17) 

[0.00976562500000000, 0.00976562500000000, 0.00976562500000000, 0.00976562500000000] 

sage: check(((5.0 / 512)^17).nextabove(), 17) 

[0.00976562500000000, 0.00976562500000000, 0.00976562500000001, 0.00976562500000000] 

sage: check(((5.0 / 512)^17).nextbelow(), 17) 

[0.00976562500000000, 0.00976562499999999, 0.00976562500000000, 0.00976562499999999] 

  

And check some non-perfect powers:: 

  

sage: check(2.0, 3) 

[1.25992104989487, 1.25992104989487, 1.25992104989488, 1.25992104989487] 

sage: check(2.0, 4) 

[1.18920711500272, 1.18920711500272, 1.18920711500273, 1.18920711500272] 

sage: check(2.0, 5) 

[1.14869835499704, 1.14869835499703, 1.14869835499704, 1.14869835499703] 

  

And some different precisions:: 

  

sage: check(RealField(20)(22/7), 19) 

[1.0621, 1.0621, 1.0622, 1.0621] 

sage: check(RealField(200)(e), 4) 

[1.2840254166877414840734205680624364583362808652814630892175, 1.2840254166877414840734205680624364583362808652814630892175, 1.2840254166877414840734205680624364583362808652814630892176, 1.2840254166877414840734205680624364583362808652814630892175] 

  

Check that :trac:`12105` is fixed:: 

  

sage: RealField(53)(0.05).nth_root(7 * 10^8) 

0.999999995720382 

""" 

if n <= 0: 

raise ValueError("n must be positive") 

  

cdef int odd = (n & 1) 

  

cdef int sgn = mpfr_sgn(self.value) 

  

if sgn < 0 and not odd: 

raise ValueError("taking an even root of a negative number") 

  

if sgn == 0 or n == 1 or not mpfr_number_p(self.value): 

return self 

  

cdef RealField_class fld = <RealField_class>self._parent 

  

if algorithm == 0 and n <= 10000 / fld.__prec: 

# This is a rough estimate for when it is probably 

# faster to call mpfr directly. (This is a pretty 

# good estimate on one particular machine, a 

# Core 2 Duo in 32-bit mode, but has not been tested 

# on other machines.) 

algorithm = 1 

  

cdef RealNumber x 

  

if algorithm == 1: 

x = self._new() 

sig_on() 

mpfr_rootn_ui(x.value, self.value, n, (<RealField_class>self._parent).rnd) 

sig_off() 

return x 

  

cdef mpfr_rnd_t rnd = (<RealField_class>self._parent).rnd 

  

cdef Integer mantissa 

cdef mp_exp_t exponent 

cdef int pow2 

cdef int exact 

  

if rnd != MPFR_RNDN: 

# We are going to implement nth_root using interval 

# arithmetic. To guarantee correct rounding, we will 

# increase the precision of the interval arithmetic until 

# the resulting interval is small enough...until the 

# interval is entirely within the interval represented 

# by a single floating-point number. 

  

# This always works, unless the correct answer is exactly 

# on the boundary point between the intervals of two 

# floating-point numbers. In round-to-nearest mode, this 

# is impossible; the boundary points are the 

# numbers which can be exactly represented as precision-{k+1} 

# floating-point numbers, but not precision-{k} numbers. 

# A precision-{k} floating-point number cannot be a perfect 

# n'th power (n >= 2) of such a number. 

  

# However, in the directed rounding modes, the boundary points 

# are the floating-point numbers themselves. So in a 

# directed rounding mode, we need to check whether this 

# floating-point number is a perfect n'th power. 

  

# Suppose this number is (a * 2^k)^n, for odd integer a 

# and arbitrary integer k. Then this number is 

# (a^n) * 2^(k*n), where a^n is odd. 

  

# We start by extracting the mantissa and exponent of (the 

# absolute value of) this number. 

  

mantissa = Integer() 

sig_on() 

exponent = mpfr_get_z_exp(mantissa.value, self.value) 

sig_off() 

mpz_abs(mantissa.value, mantissa.value) 

  

# Now, we want to divide out any powers of two in mantissa, 

# leaving it as an odd number. 

  

sig_on() 

pow2 = mpz_scan1(mantissa.value, 0) 

sig_off() 

  

if pow2 > 0: 

exponent = exponent + pow2 

sig_on() 

mpz_fdiv_q_2exp(mantissa.value, mantissa.value, pow2) 

sig_off() 

  

# Our floating-point number is equal to mantissa * 2^exponent, 

# and we know that mantissa is odd. 

  

if exponent % n == 0: 

# The exponent is a multiple of n, so it's possible that 

# we have a perfect power. Now we need to check the 

# mantissa. 

  

sig_on() 

exact = mpz_root(mantissa.value, mantissa.value, n) 

sig_off() 

  

if exact: 

# Yes, we are a perfect power. We've replaced mantissa 

# with its n'th root, so we can just build 

# the resulting floating-point number. 

  

x = self._new() 

  

sig_on() 

mpfr_set_z(x.value, mantissa.value, MPFR_RNDN) 

sig_off() 

mpfr_mul_2si(x.value, x.value, exponent / n, MPFR_RNDN) 

if sgn < 0: 

mpfr_neg(x.value, x.value, MPFR_RNDN) 

  

return x 

  

# If we got here, then we're not a perfect power of a boundary 

# point, so it's safe to use the interval arithmetic technique. 

  

from .real_mpfi import RealIntervalField 

  

cdef int prec = fld.__prec + 10 

  

cdef RealNumber lower 

cdef RealNumber upper 

  

while True: 

ifld = RealIntervalField(prec) 

intv = ifld(self) 

if sgn < 0: 

intv = -intv 

intv = (intv.log() / n).exp() 

if sgn < 0: 

intv = -intv 

lower = fld(intv.lower()) 

upper = fld(intv.upper()) 

  

if mpfr_equal_p(lower.value, upper.value): 

# Yes, we found the answer 

return lower 

  

prec = prec + 20 

  

cdef class RealLiteral(RealNumber): 

""" 

Real literals are created in preparsing and provide a way to allow 

casting into higher precision rings. 

""" 

  

cdef readonly literal 

cdef readonly int base 

  

def __init__(self, RealField_class parent, x=0, int base=10): 

""" 

Initialize ``self``. 

  

EXAMPLES:: 

  

sage: RealField(200)(float(1.3)) 

1.3000000000000000444089209850062616169452667236328125000000 

sage: RealField(200)(1.3) 

1.3000000000000000000000000000000000000000000000000000000000 

sage: 1.3 + 1.2 

2.50000000000000 

""" 

RealNumber.__init__(self, parent, x, base) 

if isinstance(x, str): 

self.base = base 

self.literal = x 

  

def __neg__(self): 

""" 

Return the negative of ``self``. 

  

EXAMPLES:: 

  

sage: RealField(300)(-1.2) 

-1.20000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 

sage: RealField(300)(-(-1.2)) 

1.20000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 

""" 

if self.literal is not None and self.literal[0] == '-': 

return RealLiteral(self._parent, self.literal[1:], self.base) 

else: 

return RealLiteral(self._parent, '-'+self.literal, self.base) 

  

def numerical_approx(self, prec=None, digits=None, algorithm=None): 

""" 

Change the precision of ``self`` to ``prec`` bits 

or ``digits`` decimal digits. 

  

INPUT: 

  

- ``prec`` -- precision in bits 

  

- ``digits`` -- precision in decimal digits (only used if 

``prec`` is not given) 

  

- ``algorithm`` -- ignored for real numbers 

  

If neither ``prec`` nor ``digits`` is given, the default 

precision is 53 bits (roughly 16 digits). 

  

OUTPUT: 

  

A ``RealNumber`` with the given precision. 

  

EXAMPLES:: 

  

sage: (1.3).numerical_approx() 

1.30000000000000 

sage: n(1.3, 120) 

1.3000000000000000000000000000000000 

  

Compare with:: 

  

sage: RealField(120)(RR(13/10)) 

1.3000000000000000444089209850062616 

sage: n(RR(13/10), 120) 

Traceback (most recent call last): 

... 

TypeError: cannot approximate to a precision of 120 bits, use at most 53 bits 

  

The result is a non-literal:: 

  

sage: type(1.3) 

<type 'sage.rings.real_mpfr.RealLiteral'> 

sage: type(n(1.3)) 

<type 'sage.rings.real_mpfr.RealNumber'> 

""" 

if prec is None: 

prec = digits_to_bits(digits) 

return RealField(prec)(self.literal) 

  

  

RR = RealField() 

  

RR_min_prec = RealField(MPFR_PREC_MIN) 

  

  

def create_RealNumber(s, int base=10, int pad=0, rnd="RNDN", int min_prec=53): 

r""" 

Return the real number defined by the string ``s`` as an element of 

``RealField(prec=n)``, where ``n`` potentially has slightly 

more (controlled by pad) bits than given by ``s``. 

  

INPUT: 

  

- ``s`` -- a string that defines a real number (or 

something whose string representation defines a number) 

  

- ``base`` -- an integer between 2 and 62 

  

- ``pad`` -- an integer = 0. 

  

- ``rnd`` -- rounding mode: 

  

- ``'RNDN'`` -- round to nearest 

- ``'RNDZ'`` -- round toward zero 

- ``'RNDD'`` -- round down 

- ``'RNDU'`` -- round up 

  

- ``min_prec`` -- number will have at least this many 

bits of precision, no matter what. 

  

EXAMPLES:: 

  

sage: RealNumber('2.3') # indirect doctest 

2.30000000000000 

sage: RealNumber(10) 

10.0000000000000 

sage: RealNumber('1.0000000000000000000000000000000000') 

1.000000000000000000000000000000000 

sage: RealField(200)(1.2) 

1.2000000000000000000000000000000000000000000000000000000000 

sage: (1.2).parent() is RR 

True 

  

We can use various bases:: 

  

sage: RealNumber("10101e2",base=2) 

84.0000000000000 

sage: RealNumber("deadbeef", base=16) 

3.73592855900000e9 

sage: RealNumber("deadbeefxxx", base=16) 

Traceback (most recent call last): 

... 

TypeError: unable to convert 'deadbeefxxx' to a real number 

sage: RealNumber("z", base=36) 

35.0000000000000 

sage: RealNumber("AAA", base=37) 

14070.0000000000 

sage: RealNumber("aaa", base=37) 

50652.0000000000 

sage: RealNumber("3.4", base="foo") 

Traceback (most recent call last): 

... 

TypeError: an integer is required 

sage: RealNumber("3.4", base=63) 

Traceback (most recent call last): 

... 

ValueError: base (=63) must be an integer between 2 and 62 

  

The rounding mode is respected in all cases:: 

  

sage: RealNumber("1.5", rnd="RNDU").parent() 

Real Field with 53 bits of precision and rounding RNDU 

sage: RealNumber("1.50000000000000000000000000000000000000", rnd="RNDU").parent() 

Real Field with 130 bits of precision and rounding RNDU 

  

TESTS:: 

  

sage: RealNumber('.000000000000000000000000000000001').prec() 

53 

sage: RealNumber('-.000000000000000000000000000000001').prec() 

53 

  

sage: RealNumber('-.123456789123456789').prec() 

60 

sage: RealNumber('.123456789123456789').prec() 

60 

sage: RealNumber('0.123456789123456789').prec() 

60 

sage: RealNumber('00.123456789123456789').prec() 

60 

sage: RealNumber('123456789.123456789').prec() 

60 

  

Make sure we've rounded up ``log(10,2)`` enough to guarantee 

sufficient precision (:trac:`10164`):: 

  

sage: ks = 5*10**5, 10**6 

sage: all(RealNumber("1." + "0"*k +"1")-1 > 0 for k in ks) 

True 

""" 

if not isinstance(s, str): 

s = str(s) 

  

# Check for a valid base 

if base < 2 or base > 62: 

raise ValueError("base (=%s) must be an integer between 2 and 62"%base) 

  

if base == 10 and min_prec == 53 and len(s) <= 15 and rnd == "RNDN": 

R = RR 

else: 

# For bases 15 and up, treat 'e' as digit 

if base <= 14 and ('e' in s or 'E' in s): 

#Figure out the exponent 

index = max( s.find('e'), s.find('E') ) 

exponent = int(s[index+1:]) 

mantissa = s[:index] 

else: 

mantissa = s 

  

#Find the first nonzero entry in rest 

sigfig_mantissa = mantissa.lstrip('-0.') 

sigfigs = len(sigfig_mantissa) - ('.' in sigfig_mantissa) 

  

if base == 10: 

# hard-code the common case 

bits = int(LOG_TEN_TWO_PLUS_EPSILON*sigfigs)+1 

else: 

bits = int(math.log(base,2)*1.00001*sigfigs)+1 

  

R = RealField(prec=max(bits+pad, min_prec), rnd=rnd) 

  

return RealLiteral(R, s, base) 

  

  

# here because this imports the other real fields 

def create_RealField(prec=53, type="MPFR", rnd="RNDN", sci_not=0): 

""" 

Create a real field with given precision, type, rounding mode and 

scientific notation. 

  

Some options are ignored for certain types (RDF for example). 

  

INPUT: 

  

- ``prec`` -- a positive integer 

  

- ``type`` -- type of real field: 

  

- ``'RDF'`` -- the Sage real field corresponding to native doubles 

- ``'Interval'`` -- real fields implementing interval arithmetic 

- ``'RLF'`` -- the real lazy field 

- ``'MPFR'`` -- floating point real numbers implemented using the MPFR 

library 

  

- ``rnd`` -- rounding mode: 

  

- ``'RNDN'`` -- round to nearest 

- ``'RNDZ'`` -- round toward zero 

- ``'RNDD'`` -- round down 

- ``'RNDU'`` -- round up 

  

- ``sci_not`` -- boolean, whether to use scientific notation for printing 

  

OUTPUT: 

  

the appropriate real field 

  

EXAMPLES:: 

  

sage: from sage.rings.real_mpfr import create_RealField 

sage: create_RealField(30) 

Real Field with 30 bits of precision 

sage: create_RealField(20, 'RDF') # ignores precision 

Real Double Field 

sage: create_RealField(60, 'Interval') 

Real Interval Field with 60 bits of precision 

sage: create_RealField(40, 'RLF') # ignores precision 

Real Lazy Field 

""" 

if type == "RDF": 

return RDF 

elif type == "Interval": 

from .real_mpfi import RealIntervalField 

return RealIntervalField(prec, sci_not) 

elif type == "Ball": 

from .real_arb import RealBallField 

return RealBallField(prec) 

elif type == "RLF": 

from .real_lazy import RLF 

return RLF 

else: 

return RealField(prec, sci_not, rnd) 

  

  

def is_RealField(x): 

""" 

Returns ``True`` if ``x`` is technically of a Python real field type. 

  

EXAMPLES:: 

  

sage: sage.rings.real_mpfr.is_RealField(RR) 

True 

sage: sage.rings.real_mpfr.is_RealField(CC) 

False 

""" 

return isinstance(x, RealField_class) 

  

def is_RealNumber(x): 

""" 

Return ``True`` if ``x`` is of type :class:`RealNumber`, meaning that it 

is an element of the MPFR real field with some precision. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_mpfr import is_RealNumber 

sage: is_RealNumber(2.5) 

True 

sage: is_RealNumber(float(2.3)) 

False 

sage: is_RealNumber(RDF(2)) 

False 

sage: is_RealNumber(pi) 

False 

""" 

return isinstance(x, RealNumber) 

  

def __create__RealField_version0(prec, sci_not, rnd): 

""" 

Create a :class:`RealField_class` by calling :func:`RealField()`. 

  

EXAMPLES:: 

  

sage: sage.rings.real_mpfr.__create__RealField_version0(53, 0, 'RNDN') 

Real Field with 53 bits of precision 

""" 

return RealField(prec, sci_not, rnd) 

  

def __create__RealNumber_version0(parent, x, base=10): 

""" 

Create a :class:`RealNumber`. 

  

EXAMPLES:: 

  

sage: sage.rings.real_mpfr.__create__RealNumber_version0(RR, 22,base=3) 

22.0000000000000 

""" 

return RealNumber(parent, x, base=base) 

  

  

cdef class RRtoRR(Map): 

cpdef Element _call_(self, x): 

""" 

EXAMPLES:: 

  

sage: from sage.rings.real_mpfr import RRtoRR 

sage: R10 = RealField(10) 

sage: R100 = RealField(100) 

sage: f = RRtoRR(R100, R10) 

sage: a = R100(1.2) 

sage: f(a) 

1.2 

sage: g = f.section() 

sage: g 

Generic map: 

From: Real Field with 10 bits of precision 

To: Real Field with 100 bits of precision 

sage: g(f(a)) # indirect doctest 

1.1992187500000000000000000000 

sage: b = R10(2).sqrt() 

sage: f(g(b)) 

1.4 

sage: f(g(b)) == b 

True 

""" 

cdef RealField_class parent = <RealField_class>self._codomain 

cdef RealNumber y = parent._new() 

if type(x) is RealLiteral: 

mpfr_set_str(y.value, str_to_bytes((<RealLiteral>x).literal), 

(<RealLiteral>x).base, parent.rnd) 

else: 

mpfr_set(y.value, (<RealNumber>x).value, parent.rnd) 

return y 

  

def section(self): 

""" 

EXAMPLES:: 

  

sage: from sage.rings.real_mpfr import RRtoRR 

sage: R10 = RealField(10) 

sage: R100 = RealField(100) 

sage: f = RRtoRR(R100, R10) 

sage: f.section() 

Generic map: 

From: Real Field with 10 bits of precision 

To: Real Field with 100 bits of precision 

""" 

return RRtoRR(self._codomain, self.domain()) 

  

cdef class ZZtoRR(Map): 

cpdef Element _call_(self, x): 

""" 

EXAMPLES:: 

  

sage: from sage.rings.real_mpfr import ZZtoRR 

sage: f = ZZtoRR(ZZ, RealField(20)) 

sage: f(123456789) # indirect doctest 

1.2346e8 

""" 

cdef RealField_class parent = <RealField_class>self._codomain 

cdef RealNumber y = parent._new() 

mpfr_set_z(y.value, (<Integer>x).value, parent.rnd) 

return y 

  

cdef class QQtoRR(Map): 

cpdef Element _call_(self, x): 

""" 

EXAMPLES:: 

  

sage: from sage.rings.real_mpfr import QQtoRR 

sage: f = QQtoRR(QQ, RealField(200)) 

sage: f(-1/3) # indirect doctest 

-0.33333333333333333333333333333333333333333333333333333333333 

""" 

cdef RealField_class parent = <RealField_class>self._codomain 

cdef RealNumber y = parent._new() 

mpfr_set_q(y.value, (<Rational>x).value, parent.rnd) 

return y 

  

cdef class double_toRR(Map): 

cpdef Element _call_(self, x): 

""" 

Takes anything that can be converted to a double. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_mpfr import double_toRR 

sage: f = double_toRR(RDF, RealField(22)) 

sage: f(RDF.pi()) # indirect doctest 

3.14159 

sage: f = double_toRR(RDF, RealField(200)) 

sage: f(RDF.pi()) 

3.1415926535897931159979634685441851615905761718750000000000 

""" 

cdef RealField_class parent = <RealField_class>self._codomain 

cdef RealNumber y = parent._new() 

mpfr_set_d(y.value, x, parent.rnd) 

return y 

  

cdef class int_toRR(Map): 

cpdef Element _call_(self, x): 

""" 

Takes Python int/long instances. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_mpfr import int_toRR 

sage: f = int_toRR(int, RR) 

sage: f(-10r) # indirect doctest 

-10.0000000000000 

sage: f(2^75) 

3.77789318629572e22 

  

Also accepts objects that can be converted to int/long:: 

  

sage: R.<x> = ZZ[] 

sage: f = int_toRR(R, RR) 

sage: f(x-x+1) 

1.00000000000000 

""" 

cdef RealField_class parent = <RealField_class>self._codomain 

cdef RealNumber y = parent._new() 

cdef int err = 0 

cdef long x_long 

cdef mpz_t x_mpz 

  

if not isinstance(x, (int, long)): 

x = int(x) 

  

integer_check_long_py(x, &x_long, &err) 

  

if not err: 

mpfr_set_si(y.value, x_long, parent.rnd) 

elif err == ERR_OVERFLOW: 

mpz_init(x_mpz) 

mpz_set_pylong(x_mpz, x) 

mpfr_set_z(y.value, x_mpz, parent.rnd) 

mpz_clear(x_mpz) 

else: 

# This should never happen 

raise TypeError("argument cannot be converted to a Python int/long") 

  

return y