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

5970

5971

5972

5973

5974

5975

5976

5977

5978

5979

5980

5981

5982

5983

5984

5985

5986

5987

5988

5989

5990

5991

5992

5993

5994

5995

5996

5997

5998

5999

6000

6001

6002

6003

6004

6005

6006

6007

6008

6009

6010

6011

6012

6013

6014

6015

6016

6017

6018

6019

6020

6021

6022

6023

6024

6025

6026

6027

6028

6029

6030

6031

6032

6033

6034

6035

6036

6037

6038

6039

6040

6041

6042

6043

6044

6045

6046

6047

6048

6049

6050

6051

6052

6053

6054

6055

6056

6057

6058

6059

6060

6061

6062

6063

6064

6065

6066

6067

6068

6069

6070

6071

6072

6073

6074

6075

6076

6077

6078

6079

6080

6081

6082

6083

6084

6085

6086

6087

6088

6089

6090

6091

6092

6093

6094

6095

6096

6097

6098

6099

6100

6101

6102

6103

6104

6105

6106

6107

6108

6109

6110

6111

6112

6113

6114

6115

6116

6117

6118

6119

6120

6121

6122

6123

6124

6125

6126

6127

6128

6129

6130

6131

6132

6133

6134

6135

6136

6137

6138

6139

6140

6141

6142

6143

6144

6145

6146

6147

6148

6149

6150

6151

6152

6153

6154

6155

6156

6157

6158

6159

6160

6161

6162

6163

6164

6165

6166

6167

6168

6169

6170

6171

6172

6173

6174

6175

6176

6177

6178

6179

6180

6181

6182

6183

6184

6185

6186

6187

6188

6189

6190

6191

6192

6193

6194

6195

6196

6197

6198

6199

6200

6201

6202

6203

6204

6205

6206

6207

6208

6209

6210

6211

6212

6213

6214

6215

6216

6217

6218

6219

6220

6221

6222

6223

6224

6225

6226

6227

6228

6229

6230

6231

6232

6233

6234

6235

6236

6237

6238

6239

6240

6241

6242

6243

6244

6245

6246

6247

6248

6249

6250

6251

6252

6253

6254

6255

6256

6257

6258

6259

6260

6261

6262

6263

6264

6265

6266

6267

6268

6269

6270

6271

6272

6273

6274

6275

6276

6277

6278

6279

6280

6281

6282

6283

6284

6285

6286

6287

6288

6289

6290

6291

6292

6293

6294

6295

6296

6297

6298

6299

6300

6301

6302

6303

6304

6305

6306

6307

6308

6309

6310

6311

6312

6313

6314

6315

6316

6317

6318

6319

6320

6321

6322

6323

6324

6325

6326

6327

6328

6329

6330

6331

6332

6333

6334

6335

6336

6337

6338

6339

6340

6341

6342

6343

6344

6345

6346

6347

6348

6349

6350

6351

6352

6353

6354

6355

6356

6357

6358

6359

6360

6361

6362

6363

6364

6365

6366

6367

6368

6369

6370

6371

6372

6373

6374

6375

6376

6377

6378

6379

6380

6381

6382

6383

6384

6385

6386

6387

6388

6389

6390

6391

6392

6393

6394

6395

6396

6397

6398

6399

6400

6401

6402

6403

6404

6405

6406

6407

6408

6409

6410

6411

6412

6413

6414

6415

6416

6417

6418

6419

6420

6421

6422

6423

6424

6425

6426

6427

6428

6429

6430

6431

6432

6433

6434

6435

6436

6437

6438

6439

6440

6441

6442

6443

6444

6445

6446

6447

6448

6449

6450

6451

6452

6453

6454

6455

6456

6457

6458

6459

6460

6461

6462

6463

6464

6465

6466

6467

6468

6469

6470

6471

6472

6473

6474

6475

6476

6477

6478

6479

6480

6481

6482

6483

6484

6485

6486

6487

6488

6489

6490

6491

6492

6493

6494

6495

6496

6497

6498

6499

6500

6501

6502

6503

6504

6505

6506

6507

6508

6509

6510

6511

6512

6513

6514

6515

6516

6517

6518

6519

6520

6521

6522

6523

6524

6525

6526

6527

6528

6529

6530

6531

6532

6533

6534

6535

6536

6537

6538

6539

6540

6541

6542

6543

6544

6545

6546

6547

6548

6549

6550

6551

6552

6553

6554

6555

6556

6557

6558

6559

6560

6561

6562

6563

6564

6565

6566

6567

6568

6569

6570

6571

6572

6573

6574

6575

6576

6577

6578

6579

6580

6581

6582

6583

6584

6585

6586

6587

6588

6589

6590

6591

6592

6593

6594

6595

6596

6597

6598

6599

6600

6601

6602

6603

6604

6605

6606

6607

6608

6609

6610

6611

6612

6613

6614

6615

6616

6617

6618

6619

6620

6621

6622

6623

6624

6625

6626

6627

6628

6629

6630

6631

6632

6633

6634

6635

6636

6637

6638

6639

6640

6641

6642

6643

6644

6645

6646

6647

6648

6649

6650

6651

6652

6653

6654

6655

6656

6657

6658

6659

6660

6661

6662

6663

6664

6665

6666

6667

6668

6669

6670

6671

6672

6673

6674

6675

6676

6677

6678

6679

6680

6681

6682

6683

6684

6685

6686

6687

6688

6689

6690

6691

6692

6693

6694

6695

6696

6697

6698

6699

6700

6701

6702

6703

6704

6705

6706

6707

6708

6709

6710

6711

6712

6713

6714

6715

6716

6717

6718

6719

6720

6721

6722

6723

6724

6725

6726

6727

6728

6729

6730

6731

6732

6733

6734

6735

6736

6737

6738

6739

6740

6741

6742

6743

6744

6745

6746

6747

6748

6749

6750

6751

6752

6753

6754

6755

6756

6757

6758

6759

6760

6761

6762

6763

6764

6765

6766

6767

6768

6769

6770

6771

6772

6773

6774

6775

6776

6777

6778

6779

6780

6781

6782

6783

6784

6785

6786

6787

6788

6789

6790

6791

6792

6793

6794

6795

6796

6797

6798

6799

6800

6801

6802

6803

6804

6805

6806

6807

6808

6809

6810

6811

6812

6813

6814

6815

6816

6817

6818

6819

6820

6821

6822

6823

6824

6825

6826

6827

6828

6829

6830

6831

6832

6833

6834

6835

6836

6837

6838

6839

6840

6841

6842

6843

6844

6845

6846

6847

6848

6849

6850

6851

6852

6853

6854

6855

6856

6857

6858

6859

6860

6861

6862

6863

6864

6865

6866

6867

6868

6869

6870

6871

6872

6873

6874

6875

6876

6877

6878

6879

6880

6881

6882

6883

6884

6885

6886

6887

6888

6889

6890

6891

6892

6893

6894

6895

6896

6897

6898

6899

6900

6901

6902

6903

6904

6905

6906

6907

6908

6909

6910

6911

6912

6913

6914

6915

6916

6917

6918

6919

6920

6921

6922

6923

6924

6925

6926

6927

6928

6929

6930

6931

6932

6933

6934

6935

6936

6937

6938

6939

6940

6941

6942

6943

6944

6945

6946

6947

6948

6949

6950

6951

6952

6953

6954

6955

6956

6957

6958

6959

6960

6961

6962

6963

6964

6965

6966

6967

6968

6969

6970

6971

6972

6973

6974

6975

6976

6977

6978

6979

6980

6981

6982

6983

6984

6985

6986

6987

6988

6989

6990

6991

6992

6993

6994

6995

6996

6997

6998

6999

7000

7001

7002

7003

7004

7005

7006

7007

7008

7009

7010

7011

7012

7013

7014

7015

7016

7017

7018

7019

7020

7021

7022

7023

7024

7025

7026

7027

7028

7029

7030

7031

7032

7033

7034

7035

7036

7037

7038

7039

7040

7041

7042

7043

7044

7045

7046

7047

7048

7049

7050

7051

7052

7053

7054

7055

7056

7057

7058

7059

7060

7061

7062

7063

7064

7065

7066

7067

7068

7069

7070

7071

7072

7073

7074

7075

7076

7077

7078

7079

7080

7081

7082

7083

7084

7085

7086

7087

7088

7089

7090

7091

7092

7093

7094

7095

7096

7097

7098

7099

7100

7101

7102

7103

7104

7105

7106

7107

7108

7109

7110

7111

7112

7113

7114

7115

7116

7117

7118

7119

7120

7121

7122

7123

7124

7125

7126

7127

7128

7129

7130

7131

7132

7133

7134

7135

7136

7137

7138

7139

7140

7141

7142

7143

7144

7145

7146

7147

7148

7149

7150

7151

7152

7153

7154

7155

7156

7157

7158

7159

7160

7161

7162

7163

7164

7165

7166

7167

7168

7169

7170

7171

7172

7173

7174

7175

7176

7177

7178

7179

7180

7181

7182

7183

7184

7185

7186

7187

7188

7189

7190

7191

7192

7193

7194

7195

7196

7197

7198

7199

7200

7201

7202

7203

7204

7205

7206

7207

7208

7209

7210

7211

7212

7213

7214

7215

7216

7217

7218

7219

7220

7221

7222

7223

7224

7225

7226

7227

7228

7229

7230

7231

7232

7233

7234

7235

7236

7237

7238

7239

7240

7241

7242

7243

7244

7245

7246

7247

7248

7249

7250

7251

7252

7253

7254

7255

7256

7257

7258

7259

7260

7261

7262

7263

7264

7265

7266

7267

7268

7269

7270

7271

7272

7273

7274

7275

7276

7277

7278

7279

7280

7281

7282

7283

7284

7285

7286

7287

7288

7289

7290

7291

7292

7293

7294

7295

7296

7297

7298

7299

7300

7301

7302

7303

7304

7305

7306

7307

7308

7309

7310

7311

7312

7313

7314

7315

7316

7317

7318

7319

7320

7321

7322

7323

7324

7325

7326

7327

7328

7329

7330

7331

7332

7333

7334

7335

7336

7337

7338

7339

7340

7341

7342

7343

7344

7345

7346

7347

7348

7349

7350

7351

7352

7353

7354

7355

7356

7357

7358

7359

7360

7361

7362

7363

7364

7365

7366

7367

7368

7369

7370

7371

7372

7373

7374

7375

7376

7377

7378

7379

7380

7381

7382

7383

7384

7385

7386

7387

7388

7389

7390

7391

7392

7393

7394

7395

7396

7397

7398

7399

7400

7401

7402

7403

7404

7405

7406

7407

7408

7409

7410

7411

7412

7413

7414

7415

7416

7417

7418

7419

7420

7421

7422

7423

7424

7425

7426

7427

7428

7429

7430

7431

7432

7433

7434

7435

7436

7437

7438

7439

7440

7441

7442

7443

7444

7445

7446

7447

7448

7449

7450

7451

7452

7453

7454

7455

7456

7457

7458

7459

7460

7461

7462

7463

7464

7465

7466

7467

7468

7469

7470

7471

7472

7473

7474

7475

7476

7477

7478

7479

7480

7481

7482

7483

7484

7485

7486

7487

7488

7489

7490

7491

7492

7493

7494

7495

7496

7497

7498

7499

7500

7501

7502

7503

7504

7505

7506

7507

7508

7509

7510

7511

7512

7513

7514

7515

7516

7517

7518

7519

7520

7521

7522

7523

7524

7525

7526

7527

7528

7529

7530

7531

7532

7533

7534

7535

7536

7537

7538

7539

7540

7541

7542

7543

7544

7545

7546

7547

7548

7549

7550

7551

7552

7553

7554

7555

7556

7557

7558

7559

7560

7561

7562

7563

7564

7565

7566

7567

7568

7569

7570

7571

7572

7573

7574

7575

7576

7577

7578

7579

7580

7581

7582

7583

7584

7585

7586

7587

7588

7589

7590

7591

7592

7593

7594

7595

7596

7597

7598

7599

7600

7601

7602

7603

7604

7605

7606

7607

7608

7609

7610

7611

7612

7613

7614

7615

7616

7617

7618

7619

7620

7621

7622

7623

7624

7625

7626

7627

7628

7629

7630

7631

7632

7633

7634

7635

7636

7637

7638

7639

7640

7641

7642

7643

7644

7645

7646

7647

7648

7649

7650

7651

7652

7653

7654

7655

7656

7657

7658

7659

7660

7661

7662

7663

7664

7665

""" 

Field of Algebraic Numbers 

 

AUTHOR: 

 

- Carl Witty (2007-01-27): initial version 

- Carl Witty (2007-10-29): massive rewrite to support complex as well as real numbers 

 

This is an implementation of the algebraic numbers (the complex 

numbers which are the zero of a polynomial in `\ZZ[x]`; in other 

words, the algebraic closure of `\QQ`, with an embedding into `\CC`). 

All computations are exact. We also include an implementation of the 

algebraic reals (the intersection of the algebraic numbers with 

`\RR`). The field of algebraic numbers `\QQbar` is available with 

abbreviation ``QQbar``; the field of algebraic reals has abbreviation 

``AA``. 

 

As with many other implementations of the algebraic numbers, we try 

hard to avoid computing a number field and working in the number 

field; instead, we use floating-point interval arithmetic whenever 

possible (basically whenever we need to prove non-equalities), and 

resort to symbolic computation only as needed (basically to prove 

equalities). 

 

Algebraic numbers exist in one of the following forms: 

 

- a rational number 

 

- the sum, difference, product, or quotient of algebraic numbers 

 

- the negation, inverse, absolute value, norm, real part, 

imaginary part, or complex conjugate of an algebraic number 

 

- a particular root of a polynomial, given as a polynomial with 

algebraic coefficients together with an isolating interval (given as 

a ``RealIntervalFieldElement``) which encloses exactly one root, and 

the multiplicity of the root 

 

- a polynomial in one generator, where the generator is an algebraic 

number given as the root of an irreducible polynomial with integral 

coefficients and the polynomial is given as a 

``NumberFieldElement``. 

 

An algebraic number can be coerced into ``ComplexIntervalField`` (or 

``RealIntervalField``, for algebraic reals); every algebraic number has a 

cached interval of the highest precision yet calculated. 

 

In most cases, computations that need to compare two algebraic numbers 

compute them with 128-bit precision intervals; if this does not suffice to 

prove that the numbers are different, then we fall back on exact 

computation. 

 

Note that division involves an implicit comparison of the divisor against 

zero, and may thus trigger exact computation. 

 

Also, using an algebraic number in the leading coefficient of 

a polynomial also involves an implicit comparison against zero, which 

again may trigger exact computation. 

 

Note that we work fairly hard to avoid computing new number fields; 

to help, we keep a lattice of already-computed number fields and 

their inclusions. 

 

EXAMPLES:: 

 

sage: sqrt(AA(2)) > 0 

True 

sage: (sqrt(5 + 2*sqrt(QQbar(6))) - sqrt(QQbar(3)))^2 == 2 

True 

sage: AA((sqrt(5 + 2*sqrt(6)) - sqrt(3))^2) == 2 

True 

 

For a monic cubic polynomial `x^3 + bx^2 + cx + d` with roots `s1`, 

`s2`, `s3`, the discriminant is defined as 

`(s1-s2)^2(s1-s3)^2(s2-s3)^2` and can be computed as `b^2c^2 - 4b^3d - 

4c^3 + 18bcd - 27d^2`. We can test that these definitions do give the 

same result:: 

 

sage: def disc1(b, c, d): 

....: return b^2*c^2 - 4*b^3*d - 4*c^3 + 18*b*c*d - 27*d^2 

sage: def disc2(s1, s2, s3): 

....: return ((s1-s2)*(s1-s3)*(s2-s3))^2 

sage: x = polygen(AA) 

sage: p = x*(x-2)*(x-4) 

sage: cp = AA.common_polynomial(p) 

sage: d, c, b, _ = p.list() 

sage: s1 = AA.polynomial_root(cp, RIF(-1, 1)) 

sage: s2 = AA.polynomial_root(cp, RIF(1, 3)) 

sage: s3 = AA.polynomial_root(cp, RIF(3, 5)) 

sage: disc1(b, c, d) == disc2(s1, s2, s3) 

True 

sage: p = p + 1 

sage: cp = AA.common_polynomial(p) 

sage: d, c, b, _ = p.list() 

sage: s1 = AA.polynomial_root(cp, RIF(-1, 1)) 

sage: s2 = AA.polynomial_root(cp, RIF(1, 3)) 

sage: s3 = AA.polynomial_root(cp, RIF(3, 5)) 

sage: disc1(b, c, d) == disc2(s1, s2, s3) 

True 

sage: p = (x-sqrt(AA(2)))*(x-AA(2).nth_root(3))*(x-sqrt(AA(3))) 

sage: cp = AA.common_polynomial(p) 

sage: d, c, b, _ = p.list() 

sage: s1 = AA.polynomial_root(cp, RIF(1.4, 1.5)) 

sage: s2 = AA.polynomial_root(cp, RIF(1.7, 1.8)) 

sage: s3 = AA.polynomial_root(cp, RIF(1.2, 1.3)) 

sage: disc1(b, c, d) == disc2(s1, s2, s3) 

True 

 

We can convert from symbolic expressions:: 

 

sage: QQbar(sqrt(-5)) 

2.236067977499790?*I 

sage: AA(sqrt(2) + sqrt(3)) 

3.146264369941973? 

sage: QQbar(I) 

I 

sage: AA(I) 

Traceback (most recent call last): 

... 

ValueError: Cannot coerce algebraic number with non-zero imaginary part to algebraic real 

sage: QQbar(I * golden_ratio) 

1.618033988749895?*I 

sage: AA(golden_ratio)^2 - AA(golden_ratio) 

1 

sage: QQbar((-8)^(1/3)) 

1.000000000000000? + 1.732050807568878?*I 

sage: AA((-8)^(1/3)) 

-2 

sage: QQbar((-4)^(1/4)) 

1 + 1*I 

sage: AA((-4)^(1/4)) 

Traceback (most recent call last): 

... 

ValueError: Cannot coerce algebraic number with non-zero imaginary part to algebraic real 

 

The coercion, however, goes in the other direction, since not all 

symbolic expressions are algebraic numbers:: 

 

sage: QQbar(sqrt(2)) + sqrt(3) 

sqrt(3) + 1.414213562373095? 

sage: QQbar(sqrt(2) + QQbar(sqrt(3))) 

3.146264369941973? 

 

Note the different behavior in taking roots: for ``AA`` we prefer real 

roots if they exist, but for ``QQbar`` we take the principal root:: 

 

sage: AA(-1)^(1/3) 

-1 

sage: QQbar(-1)^(1/3) 

0.500000000000000? + 0.866025403784439?*I 

 

We can explicitly coerce from `\QQ[I]`. (Technically, this is not quite 

kosher, since `\QQ[I]` doesn't come with an embedding; we do not know 

whether the field generator is supposed to map to `+I` or `-I`. We assume 

that for any quadratic field with polynomial `x^2+1`, the generator maps 

to `+I`.):: 

 

sage: K.<im> = QQ[I] 

sage: pythag = QQbar(3/5 + 4*im/5); pythag 

4/5*I + 3/5 

sage: pythag.abs() == 1 

True 

 

However, implicit coercion from `\QQ[I]` is not allowed:: 

 

sage: QQbar(1) + im 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for +: 'Algebraic Field' and 'Number Field in I with defining polynomial x^2 + 1' 

 

We can implicitly coerce from algebraic reals to algebraic numbers:: 

 

sage: a = QQbar(1); a, a.parent() 

(1, Algebraic Field) 

sage: b = AA(1); b, b.parent() 

(1, Algebraic Real Field) 

sage: c = a + b; c, c.parent() 

(2, Algebraic Field) 

 

Some computation with radicals:: 

 

sage: phi = (1 + sqrt(AA(5))) / 2 

sage: phi^2 == phi + 1 

True 

sage: tau = (1 - sqrt(AA(5))) / 2 

sage: tau^2 == tau + 1 

True 

sage: phi + tau == 1 

True 

sage: tau < 0 

True 

 

sage: rt23 = sqrt(AA(2/3)) 

sage: rt35 = sqrt(AA(3/5)) 

sage: rt25 = sqrt(AA(2/5)) 

sage: rt23 * rt35 == rt25 

True 

 

The Sage rings ``AA`` and ``QQbar`` can decide equalities between radical 

expressions (over the reals and complex numbers respectively):: 

 

sage: a = AA((2/(3*sqrt(3)) + 10/27)^(1/3) - 2/(9*(2/(3*sqrt(3)) + 10/27)^(1/3)) + 1/3) 

sage: a 

1.000000000000000? 

sage: a == 1 

True 

 

Algebraic numbers which are known to be rational print as rationals; 

otherwise they print as intervals (with 53-bit precision):: 

 

sage: AA(2)/3 

2/3 

sage: QQbar(5/7) 

5/7 

sage: QQbar(1/3 - 1/4*I) 

-1/4*I + 1/3 

sage: two = QQbar(4).nth_root(4)^2; two 

2.000000000000000? 

sage: two == 2; two 

True 

2 

sage: phi 

1.618033988749895? 

 

We can find the real and imaginary parts of an algebraic number (exactly):: 

 

sage: r = QQbar.polynomial_root(x^5 - x - 1, CIF(RIF(0.1, 0.2), RIF(1.0, 1.1))); r 

0.1812324444698754? + 1.083954101317711?*I 

sage: r.real() 

0.1812324444698754? 

sage: r.imag() 

1.083954101317711? 

sage: r.minpoly() 

x^5 - x - 1 

sage: r.real().minpoly() 

x^10 + 3/16*x^6 + 11/32*x^5 - 1/64*x^2 + 1/128*x - 1/1024 

sage: r.imag().minpoly() # long time (10s on sage.math, 2013) 

x^20 - 5/8*x^16 - 95/256*x^12 - 625/1024*x^10 - 5/512*x^8 - 1875/8192*x^6 + 25/4096*x^4 - 625/32768*x^2 + 2869/1048576 

 

We can find the absolute value and norm of an algebraic number exactly. 

(Note that we define the norm as the product of a number and its 

complex conjugate; this is the algebraic definition of norm, if we 

view ``QQbar`` as ``AA[I]``.):: 

 

sage: R.<x> = QQ[] 

sage: r = (x^3 + 8).roots(QQbar, multiplicities=False)[2]; r 

1.000000000000000? + 1.732050807568878?*I 

sage: r.abs() == 2 

True 

sage: r.norm() == 4 

True 

sage: (r+QQbar(I)).norm().minpoly() 

x^2 - 10*x + 13 

sage: r = AA.polynomial_root(x^2 - x - 1, RIF(-1, 0)); r 

-0.618033988749895? 

sage: r.abs().minpoly() 

x^2 + x - 1 

 

We can compute the multiplicative order of an algebraic number:: 

 

sage: QQbar(-1/2 + I*sqrt(3)/2).multiplicative_order() 

3 

sage: QQbar(-sqrt(3)/2 + I/2).multiplicative_order() 

12 

sage: (QQbar.zeta(23)**5).multiplicative_order() 

23 

 

The paper "ARPREC: An Arbitrary Precision Computation Package" by 

Bailey, Yozo, Li and Thompson discusses this result. Evidently it is 

difficult to find, but we can easily verify it. :: 

 

sage: alpha = QQbar.polynomial_root(x^10 + x^9 - x^7 - x^6 - x^5 - x^4 - x^3 + x + 1, RIF(1, 1.2)) 

sage: lhs = alpha^630 - 1 

sage: rhs_num = (alpha^315 - 1) * (alpha^210 - 1) * (alpha^126 - 1)^2 * (alpha^90 - 1) * (alpha^3 - 1)^3 * (alpha^2 - 1)^5 * (alpha - 1)^3 

sage: rhs_den = (alpha^35 - 1) * (alpha^15 - 1)^2 * (alpha^14 - 1)^2 * (alpha^5 - 1)^6 * alpha^68 

sage: rhs = rhs_num / rhs_den 

sage: lhs 

2.642040335819351?e44 

sage: rhs 

2.642040335819351?e44 

sage: lhs - rhs 

0.?e29 

sage: lhs == rhs 

True 

sage: lhs - rhs 

0 

sage: lhs._exact_value() 

-10648699402510886229334132989629606002223831*a^9 + 23174560249100286133718183712802529035435800*a^8 - 27259790692625442252605558473646959458901265*a^7 + 21416469499004652376912957054411004410158065*a^6 - 14543082864016871805545108986578337637140321*a^5 + 6458050008796664339372667222902512216589785*a^4 + 3052219053800078449122081871454923124998263*a^3 - 14238966128623353681821644902045640915516176*a^2 + 16749022728952328254673732618939204392161001*a - 9052854758155114957837247156588012516273410 where a^10 - a^9 + a^7 - a^6 + a^5 - a^4 + a^3 - a + 1 = 0 and a in -1.176280818259918? 

 

Given an algebraic number, we can produce a string that will reproduce 

that algebraic number if you type the string into Sage. We can see 

that until exact computation is triggered, an algebraic number keeps 

track of the computation steps used to produce that number:: 

 

sage: rt2 = AA(sqrt(2)) 

sage: rt3 = AA(sqrt(3)) 

sage: n = (rt2 + rt3)^5; n 

308.3018001722975? 

sage: sage_input(n) 

R.<x> = AA[] 

v1 = AA.polynomial_root(AA.common_polynomial(x^2 - 2), RIF(RR(1.4142135623730949), RR(1.4142135623730951))) + AA.polynomial_root(AA.common_polynomial(x^2 - 3), RIF(RR(1.7320508075688772), RR(1.7320508075688774))) 

v2 = v1*v1 

v2*v2*v1 

 

But once exact computation is triggered, the computation tree is discarded, 

and we get a way to produce the number directly:: 

 

sage: n == 109*rt2 + 89*rt3 

True 

sage: sage_input(n) 

R.<x> = AA[] 

v = AA.polynomial_root(AA.common_polynomial(x^4 - 4*x^2 + 1), RIF(RR(0.51763809020504148), RR(0.51763809020504159))) 

-109*v^3 - 89*v^2 + 327*v + 178 

 

We can also see that some computations (basically, those which are 

easy to perform exactly) are performed directly, instead of storing 

the computation tree:: 

 

sage: z3_3 = QQbar.zeta(3) * 3 

sage: z4_4 = QQbar.zeta(4) * 4 

sage: z5_5 = QQbar.zeta(5) * 5 

sage: sage_input(z3_3 * z4_4 * z5_5) 

R.<x> = AA[] 

3*QQbar.polynomial_root(AA.common_polynomial(x^2 + x + 1), CIF(RIF(-RR(0.50000000000000011), -RR(0.49999999999999994)), RIF(RR(0.8660254037844386), RR(0.86602540378443871))))*QQbar(4*I)*(5*QQbar.polynomial_root(AA.common_polynomial(x^4 + x^3 + x^2 + x + 1), CIF(RIF(RR(0.3090169943749474), RR(0.30901699437494745)), RIF(RR(0.95105651629515353), RR(0.95105651629515364))))) 

 

Note that the ``verify=True`` argument to ``sage_input`` will always trigger 

exact computation, so running ``sage_input`` twice in a row on the same number 

will actually give different answers. In the following, running ``sage_input`` 

on ``n`` will also trigger exact computation on ``rt2``, as you can see by the 

fact that the third output is different than the first:: 

 

sage: rt2 = AA(sqrt(2)) 

sage: n = rt2^2 

sage: sage_input(n, verify=True) 

# Verified 

R.<x> = AA[] 

v = AA.polynomial_root(AA.common_polynomial(x^2 - 2), RIF(RR(1.4142135623730949), RR(1.4142135623730951))) 

v*v 

sage: sage_input(n, verify=True) 

# Verified 

AA(2) 

sage: n = rt2^2 

sage: sage_input(n, verify=True) 

# Verified 

AA(2) 

 

Just for fun, let's try ``sage_input`` on a very complicated expression. The 

output of this example changed with the rewriting of polynomial multiplication 

algorithms in :trac:`10255`:: 

 

sage: rt2 = sqrt(AA(2)) 

sage: rt3 = sqrt(QQbar(3)) 

sage: x = polygen(QQbar) 

sage: nrt3 = AA.polynomial_root((x-rt2)*(x+rt3), RIF(-2, -1)) 

sage: one = AA.polynomial_root((x-rt2)*(x-rt3)*(x-nrt3)*(x-1-rt3-nrt3), RIF(0.9, 1.1)) 

sage: one 

1.000000000000000? 

sage: sage_input(one, verify=True) 

# Verified 

R1 = QQbar['x'] 

x1 = R1.gen() 

R2 = AA['x'] 

x2 = R2.gen() 

cp1 = AA.common_polynomial(x2^2 - 2) 

v1 = QQbar.polynomial_root(cp1, RIF(RR(1.4142135623730949), RR(1.4142135623730951))) 

v2 = QQbar.polynomial_root(AA.common_polynomial(x1^2 - 3), CIF(RIF(RR(1.7320508075688772), RR(1.7320508075688774)), RIF(RR(0)))) 

v3 = -v1 - v2 

v4 = QQbar.polynomial_root(cp1, RIF(RR(1.4142135623730949), RR(1.4142135623730951))) 

cp2 = AA.common_polynomial(x1^2 + (-v4 + v2)*x1 - v4*v2) 

v5 = QQbar.polynomial_root(cp2, RIF(-RR(1.7320508075688774), -RR(1.7320508075688772))) 

v6 = v3 - v5 

v7 = -1 - v2 - QQbar.polynomial_root(cp2, RIF(-RR(1.7320508075688774), -RR(1.7320508075688772))) 

v8 = v1*v2 

v9 = v8 - v3*v5 

si = v8*v5 

AA.polynomial_root(AA.common_polynomial(x1^4 + (v6 + v7)*x1^3 + (v9 + v6*v7)*x1^2 + (-si + v9*v7)*x1 - si*v7), RIF(RR(0.99999999999999989), RR(1.0000000000000002))) 

sage: one 

1 

 

We can pickle and unpickle algebraic fields (and they are globally unique):: 

 

sage: loads(dumps(AlgebraicField())) is AlgebraicField() 

True 

sage: loads(dumps(AlgebraicRealField())) is AlgebraicRealField() 

True 

 

We can pickle and unpickle algebraic numbers:: 

 

sage: loads(dumps(QQbar(10))) == QQbar(10) 

True 

sage: loads(dumps(QQbar(5/2))) == QQbar(5/2) 

True 

sage: loads(dumps(QQbar.zeta(5))) == QQbar.zeta(5) 

True 

 

sage: t = QQbar(sqrt(2)); type(t._descr) 

<class 'sage.rings.qqbar.ANRoot'> 

sage: loads(dumps(t)) == QQbar(sqrt(2)) 

True 

 

sage: t.exactify(); type(t._descr) 

<class 'sage.rings.qqbar.ANExtensionElement'> 

sage: loads(dumps(t)) == QQbar(sqrt(2)) 

True 

 

sage: t = ~QQbar(sqrt(2)); type(t._descr) 

<class 'sage.rings.qqbar.ANUnaryExpr'> 

sage: loads(dumps(t)) == 1/QQbar(sqrt(2)) 

True 

 

sage: t = QQbar(sqrt(2)) + QQbar(sqrt(3)); type(t._descr) 

<class 'sage.rings.qqbar.ANBinaryExpr'> 

sage: loads(dumps(t)) == QQbar(sqrt(2)) + QQbar(sqrt(3)) 

True 

 

We can convert elements of ``QQbar`` and ``AA`` into the following 

types: ``float``, ``complex``, ``RDF``, ``CDF``, ``RR``, ``CC``, 

``RIF``, ``CIF``, ``ZZ``, and ``QQ``, with a few exceptions. (For the 

arbitrary-precision types, ``RR``, ``CC``, ``RIF``, and ``CIF``, it 

can convert into a field of arbitrary precision.) 

 

Converting from ``QQbar`` to a real type (``float``, ``RDF``, ``RR``, 

``RIF``, ``ZZ``, or ``QQ``) succeeds only if the ``QQbar`` is actually 

real (has an imaginary component of exactly zero). Converting from 

either ``AA`` or ``QQbar`` to ``ZZ`` or ``QQ`` succeeds only if the 

number actually is an integer or rational. If conversion fails, a 

ValueError will be raised. 

 

Here are examples of all of these conversions:: 

 

sage: all_vals = [AA(42), AA(22/7), AA(golden_ratio), QQbar(-13), QQbar(89/55), QQbar(-sqrt(7)), QQbar.zeta(5)] 

sage: def convert_test_all(ty): 

....: def convert_test(v): 

....: try: 

....: return ty(v) 

....: except (TypeError, ValueError): 

....: return None 

....: return [convert_test(_) for _ in all_vals] 

sage: convert_test_all(float) 

[42.0, 3.1428571428571432, 1.618033988749895, -13.0, 1.6181818181818182, -2.6457513110645907, None] 

sage: convert_test_all(complex) 

[(42+0j), (3.1428571428571432+0j), (1.618033988749895+0j), (-13+0j), (1.6181818181818182+0j), (-2.6457513110645907+0j), (0.30901699437494745+0.9510565162951536j)] 

sage: convert_test_all(RDF) 

[42.0, 3.1428571428571432, 1.618033988749895, -13.0, 1.6181818181818182, -2.6457513110645907, None] 

sage: convert_test_all(CDF) 

[42.0, 3.1428571428571432, 1.618033988749895, -13.0, 1.6181818181818182, -2.6457513110645907, 0.30901699437494745 + 0.9510565162951536*I] 

sage: convert_test_all(RR) 

[42.0000000000000, 3.14285714285714, 1.61803398874989, -13.0000000000000, 1.61818181818182, -2.64575131106459, None] 

sage: convert_test_all(CC) 

[42.0000000000000, 3.14285714285714, 1.61803398874989, -13.0000000000000, 1.61818181818182, -2.64575131106459, 0.309016994374947 + 0.951056516295154*I] 

sage: convert_test_all(RIF) 

[42, 3.142857142857143?, 1.618033988749895?, -13, 1.618181818181819?, -2.645751311064591?, None] 

sage: convert_test_all(CIF) 

[42, 3.142857142857143?, 1.618033988749895?, -13, 1.618181818181819?, -2.645751311064591?, 0.3090169943749474? + 0.9510565162951536?*I] 

sage: convert_test_all(ZZ) 

[42, None, None, -13, None, None, None] 

sage: convert_test_all(QQ) 

[42, 22/7, None, -13, 89/55, None, None] 

 

Compute the exact coordinates of a 34-gon (the formulas used are from 

Weisstein, Eric W. "Trigonometry Angles--Pi/17." and can be found at 

http://mathworld.wolfram.com/TrigonometryAnglesPi17.html):: 

 

sage: rt17 = AA(17).sqrt() 

sage: rt2 = AA(2).sqrt() 

sage: eps = (17 + rt17).sqrt() 

sage: epss = (17 - rt17).sqrt() 

sage: delta = rt17 - 1 

sage: alpha = (34 + 6*rt17 + rt2*delta*epss - 8*rt2*eps).sqrt() 

sage: beta = 2*(17 + 3*rt17 - 2*rt2*eps - rt2*epss).sqrt() 

sage: x = rt2*(15 + rt17 + rt2*(alpha + epss)).sqrt()/8 

sage: y = rt2*(epss**2 - rt2*(alpha + epss)).sqrt()/8 

 

sage: cx, cy = 1, 0 

sage: for i in range(34): 

....: cx, cy = x*cx-y*cy, x*cy+y*cx 

sage: cx 

1.000000000000000? 

sage: cy 

0.?e-15 

 

sage: ax = polygen(AA) 

sage: x2 = AA.polynomial_root(256*ax**8 - 128*ax**7 - 448*ax**6 + 192*ax**5 + 240*ax**4 - 80*ax**3 - 40*ax**2 + 8*ax + 1, RIF(0.9829, 0.983)) 

sage: y2 = (1-x2**2).sqrt() 

sage: x - x2 

0.?e-18 

sage: y - y2 

0.?e-17 

 

Ideally, in the above example we should be able to test ``x == x2`` and ``y == 

y2`` but this is currently infinitely long. 

 

TESTS: 

 

Verify that :trac:`10981` is fixed:: 

 

sage: x = AA['x'].gen() 

sage: P = 1/(1+x^4) 

sage: P.partial_fraction_decomposition() 

(0, [(-0.3535533905932738?*x + 1/2)/(x^2 - 1.414213562373095?*x + 1), (0.3535533905932738?*x + 1/2)/(x^2 + 1.414213562373095?*x + 1)]) 

 

Check that :trac:`22202` is fixed:: 

 

sage: R1.<x> = AA[]; R2.<s> = QQbar[] 

sage: v = QQbar.polynomial_root(x^2 - x + 1, CIF(0.5, RIF(-0.87, -0.85))) 

sage: a = QQbar.polynomial_root((-4*v + 2)*s + (v - 1/2), CIF(RIF(0.24, 0.26), RIF(0))) 

sage: QQ(a) 

1/4 

""" 

 

from __future__ import absolute_import, print_function, division 

from six.moves import range 

from six import integer_types, iteritems 

 

import itertools 

import operator 

 

import sage.rings.ring 

from sage.misc.fast_methods import Singleton 

from sage.misc.cachefunc import cached_method 

from sage.structure.sage_object import SageObject 

from sage.structure.richcmp import (richcmp, richcmp_method, 

rich_to_bool, richcmp_not_equal, 

op_EQ, op_NE) 

from sage.rings.real_mpfr import RR 

from sage.rings.real_mpfi import RealIntervalField, RIF, is_RealIntervalFieldElement, RealIntervalField_class 

from sage.rings.complex_field import ComplexField 

from sage.rings.complex_interval_field import ComplexIntervalField, is_ComplexIntervalField 

from sage.rings.complex_interval import is_ComplexIntervalFieldElement 

from sage.rings.polynomial.all import PolynomialRing 

from sage.rings.polynomial.polynomial_element import is_Polynomial 

from sage.rings.integer_ring import ZZ 

from sage.rings.rational_field import QQ 

from sage.rings.number_field.number_field import NumberField, QuadraticField, CyclotomicField 

from sage.rings.number_field.number_field_element_quadratic import NumberFieldElement_quadratic 

from sage.arith.all import factor 

from . import infinity 

from sage.categories.action import Action 

 

 

CC = ComplexField() 

CIF = ComplexIntervalField() 

 

 

class AlgebraicField_common(sage.rings.ring.Field): 

r""" 

Common base class for the classes :class:`~AlgebraicRealField` and 

:class:`~AlgebraicField`. 

""" 

 

def default_interval_prec(self): 

r""" 

Return the default interval precision used for root isolation. 

 

EXAMPLES:: 

 

sage: AA.default_interval_prec() 

64 

""" 

 

return 64 

 

def is_finite(self): 

r""" 

Check whether this field is finite. Since this class is only used for 

fields of characteristic 0, always returns False. 

 

EXAMPLES:: 

 

sage: QQbar.is_finite() 

False 

""" 

return False 

 

def characteristic(self): 

r""" 

Return the characteristic of this field. Since this class is only used 

for fields of characteristic 0, always returns 0. 

 

EXAMPLES:: 

 

sage: AA.characteristic() 

0 

""" 

return sage.rings.integer.Integer(0) 

 

def order(self): 

r""" 

Return the cardinality of self. Since this class is only used for 

fields of characteristic 0, always returns Infinity. 

 

EXAMPLES:: 

 

sage: QQbar.order() 

+Infinity 

""" 

return infinity.infinity 

 

def common_polynomial(self, poly): 

""" 

Given a polynomial with algebraic coefficients, returns a 

wrapper that caches high-precision calculations and 

factorizations. This wrapper can be passed to polynomial_root 

in place of the polynomial. 

 

Using ``common_polynomial`` makes no semantic difference, but will 

improve efficiency if you are dealing with multiple roots 

of a single polynomial. 

 

EXAMPLES:: 

 

sage: x = polygen(ZZ) 

sage: p = AA.common_polynomial(x^2 - x - 1) 

sage: phi = AA.polynomial_root(p, RIF(1, 2)) 

sage: tau = AA.polynomial_root(p, RIF(-1, 0)) 

sage: phi + tau == 1 

True 

sage: phi * tau == -1 

True 

 

sage: x = polygen(SR) 

sage: p = (x - sqrt(-5)) * (x - sqrt(3)); p 

x^2 + (-sqrt(3) - sqrt(-5))*x + sqrt(3)*sqrt(-5) 

sage: p = QQbar.common_polynomial(p) 

sage: a = QQbar.polynomial_root(p, CIF(RIF(-0.1, 0.1), RIF(2, 3))); a 

0.?e-18 + 2.236067977499790?*I 

sage: b = QQbar.polynomial_root(p, RIF(1, 2)); b 

1.732050807568878? 

 

These "common polynomials" can be shared between real and 

complex roots:: 

 

sage: p = AA.common_polynomial(x^3 - x - 1) 

sage: r1 = AA.polynomial_root(p, RIF(1.3, 1.4)); r1 

1.324717957244746? 

sage: r2 = QQbar.polynomial_root(p, CIF(RIF(-0.7, -0.6), RIF(0.5, 0.6))); r2 

-0.6623589786223730? + 0.5622795120623013?*I 

""" 

return AlgebraicPolynomialTracker(poly) 

 

def _get_action_(self, G, op, self_on_left): 

""" 

EXAMPLES:: 

 

sage: QQbar.get_action(QQ, operator.pow) 

Right Rational Powering by Rational Field on Algebraic Field 

sage: print(QQbar.get_action(QQ, operator.pow, self_on_left=False)) 

None 

sage: print(QQbar.get_action(QQ, operator.mul)) 

None 

sage: QQbar.get_action(ZZ, operator.pow) 

Right Integer Powering by Integer Ring on Algebraic Field 

""" 

if self_on_left and G is QQ and op is operator.pow: 

return AlgebraicNumberPowQQAction(G, self) 

 

 

class AlgebraicRealField(Singleton, AlgebraicField_common): 

r""" 

The field of algebraic reals. 

 

TESTS:: 

 

sage: AA == loads(dumps(AA)) 

True 

""" 

 

def __new__(cls): 

r""" 

This method is there to ensure that pickles created before this class 

was made a :class:`~sage.misc.fast_methods.Singleton` still load. 

 

TESTS:: 

 

sage: s = loads(b'x\x9cmQ\xcbR\x141\x14\xad\x11A\x083\xe2\x03T|' 

....: b'\x82l`\xd3\xff\xe0\x86\x8de/\xba*\xcb\xa9[\xe9\xf4' 

....: b'\xa5;e:=\'I+,\xa6J\x17B\xf9\xd7f\x08\xe2s\x95\xa4\xee9\xf7<' 

....: b'\xf2\xe5\x8e\x0e\xaa\xe5"D?\xea8z.\x9a\x0b\xa7z\xa3I[\x15' 

....: b'\x82\xf8\xf3\x85\xc9\xb1<xg[\xae\xbd2\xbabeO\r\xdb\x86>\x9b' 

....: b'\xd8\x91V\x91\xdb\xc1_\xe0f\xa57\xae\r\x05P+/\xfe\xe5\x08' 

....: b'\xaci\xa2z46\x1aG$Z\x8e*F/p\xf7oC\xa33\x18\x99</<\x07v\tf' 

....: b'\x06\'F\xe7\xb9\x195\x0b\xacg\xc2\x8d\xbc\xe1P\x9c\xad\x04' 

....: b'\x828\xcd\x076N\x96W\xb8WaSN\x17\xca\xa7\r9\r\xb6.+\x88Kl' 

....: b'\x97e\xb7\x16+LO\xbeb\xb6\xc4\xfdc)\x88\xfb\x9a\x9b&\x05' 

....: b'\xc0N)wI\x0f\xee\x13\xfbH=\xc7nh(U\xc2xP\xca\r\xd2\x8d' 

....: b'\x8a\n\x0fK\xb9\xf5+\xfe\xa3n3MV\x98\x80\xc7rr\xfe\r\xbbr' 

....: b'\x9bZv\xecU\x1c|\xc0\xde\x12O\xe4:\xd5*0\x9ev3\xb9C\x0b' 

....: b'\xa3?Z\xa6\xa4\x11R6<{?I\xa2l\xb9\xbf6;\xb8\\\xc6\xe0\xb1' 

....: b'\x9f\xb3\xf6&\xe8\xe2,\xb3R\x13\xf9\xf2\xe1\xda\x9c\xc0s' 

....: b'\xb9\xf7?.\xe1E7\xeb\xa6W\x15^&\x80q&\x1aeo\x93Y\x13"^\xcd' 

....: b'\xf1Z\xee\xdf\x92W\x18Z\xa4\xa6(\xd7\x867\xdf\x93\xad\x9fL' 

....: b'\xa5W\xff\x90\x89\x07s\x1c\xfe6\xd2\x03{\xcdy\xf4v\x8e\xa3' 

....: b'\xb1.~\x000\xc2\xe0\xa1') 

sage: s is AA 

True 

 

""" 

try: return AA 

except BaseException: return AlgebraicField_common.__new__(cls) 

 

def __init__(self): 

r""" 

Standard initialization function. 

 

EXAMPLES: 

 

This function calls functions in superclasses which set the category, so we check that. 

 

sage: QQbar.category() # indirect doctest 

Category of fields 

""" 

AlgebraicField_common.__init__(self, self, ('x',), normalize=False) 

 

def _element_constructor_(self, x): 

r""" 

Construct an element of the field of algebraic real numbers from ``x``. 

 

EXAMPLES:: 

 

sage: QQbar(sqrt(2)) in AA # indirect doctest 

True 

sage: QQbar(I) in AA 

False 

sage: AA in AA 

False 

 

The following should both return True (this is a bug). :: 

 

sage: sqrt(2) in AA # not tested 

False 

sage: K.<z> = CyclotomicField(5); z + 1/z in AA # not tested 

False 

""" 

if isinstance(x, AlgebraicReal): 

return x 

elif isinstance(x, AlgebraicNumber): 

if x.imag().is_zero(): 

return x.real() 

else: 

raise ValueError("Cannot coerce algebraic number with non-zero imaginary part to algebraic real") 

elif hasattr(x, '_algebraic_'): 

return x._algebraic_(AA) 

return AlgebraicReal(x) 

 

def _repr_(self): 

r""" 

String representation of self. 

 

EXAMPLES:: 

 

sage: AA._repr_() 

'Algebraic Real Field' 

""" 

return "Algebraic Real Field" 

 

def _repr_option(self, key): 

""" 

Metadata about the :meth:`_repr_` output. 

 

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

 

EXAMPLES:: 

 

sage: AA._repr_option('element_is_atomic') 

True 

""" 

if key == 'element_is_atomic': 

return True 

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

 

# Is there a standard representation for this? 

def _latex_(self): 

r""" 

Latex representation of self. 

 

EXAMPLES:: 

 

sage: AA._latex_() 

'\\mathbf{A}' 

""" 

return "\\mathbf{A}" 

 

def _sage_input_(self, sib, coerce): 

r""" 

Produce an expression which will reproduce this value when evaluated. 

 

EXAMPLES:: 

 

sage: sage_input(AA, verify=True) 

# Verified 

AA 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: AA._sage_input_(SageInputBuilder(), False) 

{atomic:AA} 

""" 

return sib.name('AA') 

 

def _coerce_map_from_(self, from_par): 

r""" 

Set up the coercion model. 

 

TESTS:: 

 

sage: AA.has_coerce_map_from(ZZ) # indirect doctest 

True 

sage: K.<a> = QuadraticField(7, embedding=AA(7).sqrt()); AA.has_coerce_map_from(K) 

True 

sage: a in AA 

True 

sage: a + AA(3) 

5.645751311064590? 

sage: AA.has_coerce_map_from(SR) 

False 

""" 

return (from_par is ZZ or from_par is QQ 

or from_par is AA) 

 

def completion(self, p, prec, extras = {}): 

r""" 

Return the completion of self at the place `p`. Only implemented for `p 

= \infty` at present. 

 

INPUT: 

 

- ``p`` -- either a prime (not implemented at present) or Infinity 

- ``prec`` -- precision of approximate field to return 

- ``extras`` -- a dict of extra keyword arguments for the ``RealField`` 

constructor 

 

EXAMPLES:: 

 

sage: AA.completion(infinity, 500) 

Real Field with 500 bits of precision 

sage: AA.completion(infinity, prec=53, extras={'type':'RDF'}) 

Real Double Field 

sage: AA.completion(infinity, 53) is RR 

True 

sage: AA.completion(7, 10) 

Traceback (most recent call last): 

... 

NotImplementedError 

""" 

if p == infinity.Infinity: 

from sage.rings.real_mpfr import create_RealField 

return create_RealField(prec, **extras) 

else: 

raise NotImplementedError 

 

def algebraic_closure(self): 

""" 

Return the algebraic closure of this field, which is the field 

`\overline{\QQ}` of algebraic numbers. 

 

EXAMPLES:: 

 

sage: AA.algebraic_closure() 

Algebraic Field 

""" 

return QQbar 

 

def _is_valid_homomorphism_(self, codomain, im_gens): 

r""" 

Attempt to construct a homomorphism from self to codomain sending the 

generators to ``im_gens``. Since this field is not finitely generated, 

this cannot be implemented in a mathematically sensible way, and we 

just test that there exists a canonical coercion. 

 

EXAMPLES:: 

 

sage: AA._is_valid_homomorphism_(QQbar, [QQbar(1)]) 

True 

sage: AA._is_valid_homomorphism_(QQ, [QQ(1)]) 

False 

""" 

try: 

return im_gens[0] == codomain._coerce_(self.gen(0)) 

except TypeError: 

return False 

 

def gens(self): 

r""" 

Return a set of generators for this field. As this field is not 

finitely generated, we opt for just returning 1. 

 

EXAMPLES:: 

 

sage: AA.gens() 

(1,) 

""" 

return (self(1), ) 

 

def gen(self, n=0): 

r""" 

Return the `n`-th element of the tuple returned by :meth:`gens`. 

 

EXAMPLES:: 

 

sage: AA.gen(0) 

1 

sage: AA.gen(1) 

Traceback (most recent call last): 

... 

IndexError: n must be 0 

""" 

if n == 0: 

return self(1) 

else: 

raise IndexError("n must be 0") 

 

def ngens(self): 

r""" 

Return the size of the tuple returned by :meth:`gens`. 

 

EXAMPLES:: 

 

sage: AA.ngens() 

1 

""" 

return 1 

 

def zeta(self, n=2): 

r""" 

Return an `n`-th root of unity in this field. This will raise a 

``ValueError`` if `n \ne \{1, 2\}` since no such root exists. 

 

INPUT: 

 

- ``n`` (integer) -- default 2 

 

EXAMPLES:: 

 

sage: AA.zeta(1) 

1 

sage: AA.zeta(2) 

-1 

sage: AA.zeta() 

-1 

sage: AA.zeta(3) 

Traceback (most recent call last): 

... 

ValueError: no n-th root of unity in algebraic reals 

 

Some silly inputs:: 

 

sage: AA.zeta(Mod(-5, 7)) 

-1 

sage: AA.zeta(0) 

Traceback (most recent call last): 

... 

ValueError: no n-th root of unity in algebraic reals 

""" 

if n == 1: 

return self(1) 

elif n == 2: 

return self(-1) 

else: 

raise ValueError("no n-th root of unity in algebraic reals") 

 

def polynomial_root(self, poly, interval, multiplicity=1): 

r""" 

Given a polynomial with algebraic coefficients and an interval 

enclosing exactly one root of the polynomial, constructs 

an algebraic real representation of that root. 

 

The polynomial need not be irreducible, or even squarefree; but 

if the given root is a multiple root, its multiplicity must be 

specified. (IMPORTANT NOTE: Currently, multiplicity-`k` roots 

are handled by taking the `(k-1)`-st derivative of the polynomial. 

This means that the interval must enclose exactly one root 

of this derivative.) 

 

The conditions on the arguments (that the interval encloses exactly 

one root, and that multiple roots match the given multiplicity) 

are not checked; if they are not satisfied, an error may be 

thrown (possibly later, when the algebraic number is used), 

or wrong answers may result. 

 

Note that if you are constructing multiple roots of a single 

polynomial, it is better to use ``AA.common_polynomial`` (or 

``QQbar.common_polynomial``; the two are equivalent) to get a 

shared polynomial. 

 

EXAMPLES:: 

 

sage: x = polygen(AA) 

sage: phi = AA.polynomial_root(x^2 - x - 1, RIF(1, 2)); phi 

1.618033988749895? 

sage: p = (x-1)^7 * (x-2) 

sage: r = AA.polynomial_root(p, RIF(9/10, 11/10), multiplicity=7) 

sage: r; r == 1 

1.000000000000000? 

True 

sage: p = (x-phi)*(x-sqrt(AA(2))) 

sage: r = AA.polynomial_root(p, RIF(1, 3/2)) 

sage: r; r == sqrt(AA(2)) 

1.414213562373095? 

True 

 

We allow complex polynomials, as long as the particular root 

in question is real. :: 

 

sage: K.<im> = QQ[I] 

sage: x = polygen(K) 

sage: p = (im + 1) * (x^3 - 2); p 

(I + 1)*x^3 - 2*I - 2 

sage: r = AA.polynomial_root(p, RIF(1, 2)); r^3 

2.000000000000000? 

""" 

if not is_RealIntervalFieldElement(interval): 

raise ValueError("interval argument of .polynomial_root on algebraic real field must be real") 

 

return AlgebraicReal(ANRoot(poly, interval, multiplicity)) 

 

def _factor_univariate_polynomial(self, f): 

""" 

Factor the univariate polynomial ``f``. 

 

INPUT: 

 

- ``f`` -- a univariate polynomial defined over the real algebraic field 

 

OUTPUT: 

 

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

and monic irreducible factors 

 

.. NOTE:: 

 

This is a helper method for 

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

 

TESTS:: 

 

sage: R.<x> = AA[] 

sage: AA._factor_univariate_polynomial(x) 

x 

sage: AA._factor_univariate_polynomial(2*x) 

(2) * x 

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

(x^2 + 1)^2 

sage: AA._factor_univariate_polynomial(x^8 + 1) 

(x^2 - 1.847759065022574?*x + 1.000000000000000?) * (x^2 - 0.7653668647301795?*x + 1.000000000000000?) * (x^2 + 0.7653668647301795?*x + 1.000000000000000?) * (x^2 + 1.847759065022574?*x + 1.000000000000000?) 

sage: AA._factor_univariate_polynomial(R(3)) 

3 

sage: AA._factor_univariate_polynomial(12*x^2 - 4) 

(12) * (x - 0.5773502691896258?) * (x + 0.5773502691896258?) 

sage: AA._factor_univariate_polynomial(12*x^2 + 4) 

(12) * (x^2 + 0.3333333333333334?) 

sage: AA._factor_univariate_polynomial(EllipticCurve('11a1').change_ring(AA).division_polynomial(5)) 

(5) * (x - 16.00000000000000?) * (x - 5.000000000000000?) * (x - 1.959674775249769?) * (x + 2.959674775249769?) * (x^2 - 2.854101966249685?*x + 15.47213595499958?) * (x^2 + 1.909830056250526?*x + 1.660606461254312?) * (x^2 + 3.854101966249685?*x + 6.527864045000421?) * (x^2 + 13.09016994374948?*x + 93.33939353874569?) 

 

""" 

rr = f.roots() 

cr = [(r,e) for r,e in f.roots(QQbar) if r.imag()>0] 

 

from sage.structure.factorization import Factorization 

return Factorization( 

[(f.parent()([-r,1]),e) for r,e in rr] + 

[(f.parent()([r.norm(),-2*r.real(),1]),e) for r,e in cr], 

unit=f.leading_coefficient()) 

 

def is_AlgebraicRealField(F): 

r""" 

Check whether ``F`` is an :class:`~AlgebraicRealField` instance. For internal use. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import is_AlgebraicRealField 

sage: [is_AlgebraicRealField(x) for x in [AA, QQbar, None, 0, "spam"]] 

[True, False, False, False, False] 

""" 

return isinstance(F, AlgebraicRealField) 

 

# Create the globally unique AlgebraicRealField object. 

AA = AlgebraicRealField() 

 

class AlgebraicField(Singleton, AlgebraicField_common): 

""" 

The field of all algebraic complex numbers. 

""" 

 

def __new__(cls): 

r""" 

This method is there to ensure that pickles created before this class 

was made a :class:`~sage.misc.fast_methods.Singleton` still load. 

 

TESTS:: 

 

sage: s = loads(b'x\x9c}RMo\x131\x10U(-\xad\x9b\x92\x16ZJh\x80~' 

....: b'\x00MZX~\x03\x97J\x08\xb1\x87H>F\x96\xd7;\xdd\xb1\xd8x3\xb6' 

....: b'\x17\xe8!\x12\x1c\xda\xaa\xff\x9aI\xb7\x04\x8a*N\xb65\xef' 

....: b'\xcd\xbc\xf7\xc6?\xee\x99\xa0\x0bHB\xf4\xb5\x89\xb5' 

....: b'\x87$?szl\x8d2\xa5\x0eA\xdc~Q\xab/{\x1f\xca\x022\xaf\xad9' 

....: b'\xb1P\xe6\xea\x9b\x8d\xa8\x8c\x8ePT\xfe\x8cn\xday\xeb\x8a' 

....: b'\x90\x10e\xda\x8b\xdbxA\x0bF\xa9\xac\xb6e\xb4N)Q@\xd41zA' 

....: b'\xf7\xff\x15R;K5(\x0f\x13\x0f\x01\x1c\xc3l\xe5D\xed<\xe4' 

....: b'\xb5\x01A\x8b\r\xe1f\xb4\x85\x90\x9c\xce\x06\x04q\xd2\x1c' 

....: b'\xb44\x98^\xd2\x83!-\xcb\xf6D{\xee\xd0\xb8\xa0\x95\x8b!\x89' 

....: b'\x0bZMS\\\x88Cj\x0f~\xd2\xda\x94\x1e\xf6\xa5P0\xce \xcfY<uR' 

....: b'\xb9\xa9L\xe5\xbe\x82\x8fj\x0c\x11\xab\\q\x14@\xeb\xa9\\R&' 

....: b'\xd7Q\xd3F*W\xfeX\x7f\x84\xcb\\\x99a\x02=\x96\xad\x8f\xe7' 

....: b'\xb4)WU\x01\x0e\xbc\x8e\x95\x0f\xb45\xa5\'rQe:\x00m#G\xb9;' 

....: b'\x8ff\x08\xba\xbc+\xce\xa7\xff\x89s\xce\x11\xd4E\xf6\xf3' 

....: b'\x8c\xfdt\xd9\xcf\x0e\xfb\xe9M\xe9y\x1f;)\xae\xa7\xb8' 

....: b'\x91"KC\x96\xf4\xfd\x9c^ \xabx\x89\xdb\xd8\x93\x1d5\xb1' 

....: b'\xe6K\t\x8a-\x06\x8e\x96v?\xb5\xd83\x940\xbe\xce\xaar' 

....: b'\xcd.*O{\x8d\x8c\xb1\r&9mX\xbc\x88\xe6\xf2\xf9:\x1bA\xfbr' 

....: b'\xeb.\xae\xa2\x03\xec\xe1\xce\xe5\x90^1\xc0:\x1b\xad.\xe7' 

....: b'\xc1\x966Dz=\xa27\xb2;\'\xcf0j\xc2\x8bR\xcd\xd6\xe8\xf0' 

....: b'\x8ae\xfdfj3\xfb\x06\r\xb1?\xa2\xc1_%S\x817\xd0\x94' 

....: b'\x8eFt\\g\xc8\x96p\x0f\xf7\xf1\x00\xd7\xb0\xcd\x1a\xde"' 

....: b'\x0f{\x87\x87W\xc8\xdc\x04\x19\xf5\xbe\xce\x92_p\'\x13\xc5') 

sage: s is QQbar 

True 

""" 

try: return QQbar 

except BaseException: return AlgebraicField_common.__new__(cls) 

 

def __init__(self): 

r""" 

Standard init function. 

 

We test by setting the category:: 

 

sage: QQbar.category() # indirect doctest 

Category of fields 

sage: QQbar.base_ring() 

Algebraic Real Field 

 

TESTS:: 

 

sage: QQbar._repr_option('element_is_atomic') 

False 

""" 

AlgebraicField_common.__init__(self, AA, ('I',), normalize=False) 

 

def _element_constructor_(self, x): 

""" 

Try to construct an element of the field of algebraic numbers from `x`. 

 

EXAMPLES:: 

 

sage: sqrt(2) in QQbar # indirect doctest 

True 

sage: 22/7 in QQbar 

True 

sage: pi in QQbar 

False 

""" 

if isinstance(x, AlgebraicNumber): 

return x 

elif isinstance(x, AlgebraicReal): 

return AlgebraicNumber(x._descr) 

elif hasattr(x, '_algebraic_'): 

return x._algebraic_(QQbar) 

return AlgebraicNumber(x) 

 

def _repr_(self): 

r""" 

String representation of self. 

 

EXAMPLES:: 

 

sage: QQbar._repr_() 

'Algebraic Field' 

""" 

return "Algebraic Field" 

 

def _latex_(self): 

r""" 

Latex representation of self. 

 

EXAMPLES:: 

 

sage: QQbar._latex_() 

'\\overline{\\QQ}' 

""" 

return "\\overline{\\QQ}" 

 

def _sage_input_(self, sib, coerce): 

r""" 

Produce an expression which will reproduce this value when evaluated. 

 

EXAMPLES:: 

 

sage: sage_input(QQbar, verify=True) 

# Verified 

QQbar 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: QQbar._sage_input_(SageInputBuilder(), False) 

{atomic:QQbar} 

""" 

return sib.name('QQbar') 

 

def _coerce_map_from_(self, from_par): 

r""" 

Set up the coercion model. 

 

TESTS:: 

 

sage: QQbar.has_coerce_map_from(ZZ) # indirect doctest 

True 

sage: QQbar.has_coerce_map_from(AA) 

True 

sage: QQbar.has_coerce_map_from(CC) 

False 

sage: QQbar.has_coerce_map_from(SR) 

False 

""" 

return (from_par is ZZ or from_par is QQ 

or from_par is AA or from_par is QQbar) 

 

def completion(self, p, prec, extras = {}): 

r""" 

Return the completion of self at the place `p`. Only implemented for `p 

= \infty` at present. 

 

INPUT: 

 

- ``p`` -- either a prime (not implemented at present) or Infinity 

- ``prec`` -- precision of approximate field to return 

- ``extras`` -- a dict of extra keyword arguments for the ``RealField`` 

constructor 

 

EXAMPLES:: 

 

sage: QQbar.completion(infinity, 500) 

Complex Field with 500 bits of precision 

sage: QQbar.completion(infinity, prec=53, extras={'type':'RDF'}) 

Complex Double Field 

sage: QQbar.completion(infinity, 53) is CC 

True 

sage: QQbar.completion(3, 20) 

Traceback (most recent call last): 

... 

NotImplementedError 

""" 

if p == infinity.Infinity: 

from sage.rings.real_mpfr import create_RealField 

return create_RealField(prec, **extras).complex_field() 

else: 

raise NotImplementedError 

 

def algebraic_closure(self): 

""" 

Return the algebraic closure of this field. As this field is already 

algebraically closed, just returns self. 

 

EXAMPLES:: 

 

sage: QQbar.algebraic_closure() 

Algebraic Field 

""" 

return self 

 

def construction(self): 

""" 

Return a functor that constructs self (used by the coercion machinery). 

 

EXAMPLES:: 

 

sage: QQbar.construction() 

(AlgebraicClosureFunctor, Rational Field) 

""" 

from sage.categories.pushout import AlgebraicClosureFunctor 

from sage.all import QQ 

return (AlgebraicClosureFunctor(), QQ) 

 

def gens(self): 

r""" 

Return a set of generators for this field. As this field is not 

finitely generated over its prime field, we opt for just returning I. 

 

EXAMPLES:: 

 

sage: QQbar.gens() 

(I,) 

""" 

return(QQbar_I, ) 

 

def gen(self, n=0): 

r""" 

Return the `n`-th element of the tuple returned by :meth:`gens`. 

 

EXAMPLES:: 

 

sage: QQbar.gen(0) 

I 

sage: QQbar.gen(1) 

Traceback (most recent call last): 

... 

IndexError: n must be 0 

""" 

if n == 0: 

return QQbar_I 

else: 

raise IndexError("n must be 0") 

 

def ngens(self): 

r""" 

Return the size of the tuple returned by :meth:`gens`. 

 

EXAMPLES:: 

 

sage: QQbar.ngens() 

1 

""" 

return 1 

 

@cached_method 

def zeta(self, n=4): 

r""" 

Returns a primitive `n`'th root of unity, specifically `\exp(2*\pi*i/n)`. 

 

INPUT: 

 

- ``n`` (integer) -- default 4 

 

EXAMPLES:: 

 

sage: QQbar.zeta(1) 

1 

sage: QQbar.zeta(2) 

-1 

sage: QQbar.zeta(3) 

-0.500000000000000? + 0.866025403784439?*I 

sage: QQbar.zeta(4) 

I 

sage: QQbar.zeta() 

I 

sage: QQbar.zeta(5) 

0.3090169943749474? + 0.9510565162951536?*I 

sage: QQbar.zeta(3000) 

0.999997806755380? + 0.002094393571219374?*I 

""" 

if n == 1: 

return self.one() 

elif n == 2: 

return -self.one() 

elif n == 4: 

return self.gen() 

else: 

nf = CyclotomicField(n) 

p = nf.polynomial() 

root = ANRoot(p, ComplexIntervalField(64).zeta(n)) 

gen = AlgebraicGenerator(nf, root) 

return AlgebraicNumber(ANExtensionElement(gen, nf.gen())) 

 

def polynomial_root(self, poly, interval, multiplicity=1): 

r""" 

Given a polynomial with algebraic coefficients and an interval 

enclosing exactly one root of the polynomial, constructs 

an algebraic real representation of that root. 

 

The polynomial need not be irreducible, or even squarefree; but 

if the given root is a multiple root, its multiplicity must be 

specified. (IMPORTANT NOTE: Currently, multiplicity-`k` roots 

are handled by taking the `(k-1)`-st derivative of the polynomial. 

This means that the interval must enclose exactly one root 

of this derivative.) 

 

The conditions on the arguments (that the interval encloses exactly 

one root, and that multiple roots match the given multiplicity) 

are not checked; if they are not satisfied, an error may be 

thrown (possibly later, when the algebraic number is used), 

or wrong answers may result. 

 

Note that if you are constructing multiple roots of a single 

polynomial, it is better to use ``QQbar.common_polynomial`` 

to get a shared polynomial. 

 

EXAMPLES:: 

 

sage: x = polygen(QQbar) 

sage: phi = QQbar.polynomial_root(x^2 - x - 1, RIF(0, 2)); phi 

1.618033988749895? 

sage: p = (x-1)^7 * (x-2) 

sage: r = QQbar.polynomial_root(p, RIF(9/10, 11/10), multiplicity=7) 

sage: r; r == 1 

1 

True 

sage: p = (x-phi)*(x-sqrt(QQbar(2))) 

sage: r = QQbar.polynomial_root(p, RIF(1, 3/2)) 

sage: r; r == sqrt(QQbar(2)) 

1.414213562373095? 

True 

""" 

return AlgebraicNumber(ANRoot(poly, interval, multiplicity)) 

 

def random_element(self, poly_degree=2, *args, **kwds): 

r""" 

Returns a random algebraic number. 

 

INPUT: 

 

- ``poly_degree`` - default: 2 - degree of the random polynomial over 

the integers of which the returned algebraic number is a root. This 

is not necessarily the degree of the minimal polynomial of the 

number. Increase this parameter to achieve a greater diversity of 

algebraic numbers, at a cost of greater computation time. You can 

also vary the distribution of the coefficients but that will not vary 

the degree of the extension containing the element. 

 

- ``args``, ``kwds`` - arguments and keywords passed to the random 

number generator for elements of ``ZZ``, the integers. See 

:meth:`~sage.rings.integer_ring.IntegerRing_class.random_element` for 

details, or see example below. 

 

OUTPUT: 

 

An element of ``QQbar``, the field of algebraic numbers (see 

:mod:`sage.rings.qqbar`). 

 

ALGORITHM: 

 

A polynomial with degree between 1 and ``poly_degree``, 

with random integer coefficients is created. A root of this 

polynomial is chosen at random. The default degree is 

2 and the integer coefficients come from a distribution 

heavily weighted towards `0, \pm 1, \pm 2`. 

 

EXAMPLES:: 

 

sage: a = QQbar.random_element() 

sage: a # random 

0.2626138748742799? + 0.8769062830975992?*I 

sage: a in QQbar 

True 

 

sage: b = QQbar.random_element(poly_degree=20) 

sage: b # random 

-0.8642649077479498? - 0.5995098147478391?*I 

sage: b in QQbar 

True 

 

Parameters for the distribution of the integer coefficients 

of the polynomials can be passed on to the random element method 

for integers. For example, current default behavior of this method 

returns zero about 15% of the time; if we do not include zero as a 

possible coefficient, there will never be a zero constant term, and 

thus never a zero root. :: 

 

sage: z = [QQbar.random_element(x=1, y=10) for _ in range(20)] 

sage: QQbar(0) in z 

False 

 

If you just want real algebraic numbers you can filter them out. 

Using an odd degree for the polynomials will insure some degree of 

success. :: 

 

sage: r = [] 

sage: while len(r) < 3: 

....: x = QQbar.random_element(poly_degree=3) 

....: if x in AA: 

....: r.append(x) 

sage: (len(r) == 3) and all([z in AA for z in r]) 

True 

 

TESTS: 

 

sage: QQbar.random_element('junk') 

Traceback (most recent call last): 

... 

TypeError: polynomial degree must be an integer, not junk 

sage: QQbar.random_element(poly_degree=0) 

Traceback (most recent call last): 

... 

ValueError: polynomial degree must be greater than zero, not 0 

 

Random vectors already have a 'degree' keyword, so 

we cannot use that for the polynomial's degree. :: 

 

sage: v = random_vector(QQbar, degree=2, poly_degree=3) 

sage: v # random 

(0.4694381338921299?, -0.500000000000000? + 0.866025403784439?*I) 

""" 

import sage.rings.all 

import sage.misc.prandom 

try: 

poly_degree = sage.rings.all.ZZ(poly_degree) 

except TypeError: 

msg = "polynomial degree must be an integer, not {0}" 

raise TypeError(msg.format(poly_degree)) 

if poly_degree < 1: 

msg = "polynomial degree must be greater than zero, not {0}" 

raise ValueError(msg.format(poly_degree)) 

R = PolynomialRing(sage.rings.all.ZZ, 'x') 

p = R.random_element(degree=poly_degree, *args, **kwds) 

# degree zero polynomials have no roots 

# totally zero poly has degree -1 

# add a random leading term 

if p.degree() < 1: 

g = R.gen(0) 

m = sage.misc.prandom.randint(1, poly_degree) 

p = p + g**m 

roots = p.roots(ring=QQbar, multiplicities=False) 

 

# p will have at least one root; pick one at random 

# could we instead just compute one root "randomly"? 

m = sage.misc.prandom.randint(0, len(roots)-1) 

return roots[m] 

 

def _is_irreducible_univariate_polynomial(self, f): 

r""" 

Return whether ``f`` is irreducible. 

 

INPUT: 

 

- ``f`` -- a non-constant univariate polynomial defined over the 

algebraic field 

 

.. NOTE:: 

 

This is a helper method for 

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

 

EXAMPLES:: 

 

sage: R.<x> = QQbar[] 

sage: (x^2).is_irreducible() # indirect doctest 

False 

 

Note that this method does not handle constant polynomials:: 

 

sage: QQbar._is_irreducible_univariate_polynomial(R(1)) 

Traceback (most recent call last): 

... 

ValueError: polynomial must not be constant 

sage: R(1).is_irreducible() 

False 

 

""" 

if f.degree() < 1: 

# this case is handled by the caller (PolynomialElement.is_irreducible()) 

raise ValueError("polynomial must not be constant") 

 

return f.degree() == 1 

 

def _factor_univariate_polynomial(self, f): 

""" 

Factor the univariate polynomial ``f``. 

 

INPUT: 

 

- ``f`` -- a univariate polynomial defined over the algebraic field 

 

OUTPUT: 

 

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

monic irreducible factors 

 

.. NOTE:: 

 

This is a helper method for 

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

 

TESTS:: 

 

sage: R.<x> = QQbar[] 

sage: QQbar._factor_univariate_polynomial(x) 

x 

sage: QQbar._factor_univariate_polynomial(2*x) 

(2) * x 

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

(x - I)^2 * (x + I)^2 

sage: QQbar._factor_univariate_polynomial(x^8 - 1) 

(x - 1) * (x - 0.7071067811865475? - 0.7071067811865475?*I) * (x - 0.7071067811865475? + 0.7071067811865475?*I) * (x - I) * (x + I) * (x + 0.7071067811865475? - 0.7071067811865475?*I) * (x + 0.7071067811865475? + 0.7071067811865475?*I) * (x + 1) 

sage: QQbar._factor_univariate_polynomial(12*x^2 - 4) 

(12) * (x - 0.5773502691896258?) * (x + 0.5773502691896258?) 

sage: QQbar._factor_univariate_polynomial(R(-1)) 

-1 

sage: QQbar._factor_univariate_polynomial(EllipticCurve('11a1').change_ring(QQbar).division_polynomial(5)) 

(5) * (x - 16) * (x - 5) * (x - 1.959674775249769?) * (x - 1.427050983124843? - 3.665468789467727?*I) * (x - 1.427050983124843? + 3.665468789467727?*I) * (x + 0.9549150281252629? - 0.8652998037182486?*I) * (x + 0.9549150281252629? + 0.8652998037182486?*I) * (x + 1.927050983124843? - 1.677599044300515?*I) * (x + 1.927050983124843? + 1.677599044300515?*I) * (x + 2.959674775249769?) * (x + 6.545084971874737? - 7.106423590645660?*I) * (x + 6.545084971874737? + 7.106423590645660?*I) 

 

""" 

from sage.structure.factorization import Factorization 

return Factorization([(f.parent()([-r,1]),e) for r,e in f.roots()], unit=f.leading_coefficient()) 

 

def is_AlgebraicField(F): 

r""" 

Check whether ``F`` is an :class:`~AlgebraicField` instance. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import is_AlgebraicField 

sage: [is_AlgebraicField(x) for x in [AA, QQbar, None, 0, "spam"]] 

[False, True, False, False, False] 

""" 

return isinstance(F, AlgebraicField) 

 

# Create the globally unique AlgebraicField object. 

QQbar = AlgebraicField() 

 

def is_AlgebraicField_common(F): 

r""" 

Check whether ``F`` is an :class:`~AlgebraicField_common` instance. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import is_AlgebraicField_common 

sage: [is_AlgebraicField_common(x) for x in [AA, QQbar, None, 0, "spam"]] 

[True, True, False, False, False] 

""" 

return isinstance(F, AlgebraicField_common) 

 

def prec_seq(): 

r""" 

Return a generator object which iterates over an infinite increasing 

sequence of precisions to be tried in various numerical computations. 

 

Currently just returns powers of 2 starting at 64. 

 

EXAMPLES:: 

 

sage: g = sage.rings.qqbar.prec_seq() 

sage: [next(g), next(g), next(g)] 

[64, 128, 256] 

""" 

# XXX Should do some testing to see where the efficiency breaks are 

# in MPFR. We could also test variants like "bits = bits + bits // 2" 

# (I think this is what MPFR uses internally). 

bits = 64 

while True: 

yield bits 

bits = bits * 2 

 

_short_prec_seq = (64, 128, None) 

def short_prec_seq(): 

r""" 

Return a sequence of precisions to try in cases when an infinite-precision 

computation is possible: returns a couple of small powers of 2 and then 

``None``. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import short_prec_seq 

sage: short_prec_seq() 

(64, 128, None) 

""" 

return _short_prec_seq 

 

def tail_prec_seq(): 

r""" 

A generator over precisions larger than those in :func:`~short_prec_seq`. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import tail_prec_seq 

sage: g = tail_prec_seq() 

sage: [next(g), next(g), next(g)] 

[256, 512, 1024] 

""" 

bits = 256 

while True: 

yield bits 

bits = bits * 2 

 

def rational_exact_root(r, d): 

r""" 

Checks whether the rational `r` is an exact `d`'th power. If so, returns 

the `d`'th root of `r`; otherwise, returns None. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import rational_exact_root 

sage: rational_exact_root(16/81, 4) 

2/3 

sage: rational_exact_root(8/81, 3) is None 

True 

""" 

num = r.numerator() 

den = r.denominator() 

 

(num_rt, num_exact) = num.nth_root(d, truncate_mode=1) 

if not num_exact: return None 

(den_rt, den_exact) = den.nth_root(d, truncate_mode=1) 

if not den_exact: return None 

return (num_rt / den_rt) 

 

def clear_denominators(poly): 

""" 

Takes a monic polynomial and rescales the variable to get a monic 

polynomial with "integral" coefficients. Works on any univariate 

polynomial whose base ring has a ``denominator()`` method that returns 

integers; for example, the base ring might be `\QQ` or a number 

field. 

 

Returns the scale factor and the new polynomial. 

 

(Inspired by Pari's ``primitive_pol_to_monic()``.) 

 

We assume that coefficient denominators are "small"; the algorithm 

factors the denominators, to give the smallest possible scale factor. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import clear_denominators 

 

sage: _.<x> = QQ['x'] 

sage: clear_denominators(x + 3/2) 

(2, x + 3) 

sage: clear_denominators(x^2 + x/2 + 1/4) 

(2, x^2 + x + 1) 

 

""" 

 

# This algorithm factors the polynomial denominators. 

# We should check the size of the denominators and switch to 

# an alternate, less precise algorithm if we decide factoring 

# would be too slow. 

 

d = poly.denominator() 

if d == 1: 

return d, poly 

deg = poly.degree() 

factors = {} 

for i in range(deg): 

d = poly[i].denominator() 

df = factor(d) 

for f, e in df: 

oe = 0 

if f in factors: 

oe = factors[f] 

min_e = (e + (deg-i) - 1) // (deg-i) 

factors[f] = max(oe, min_e) 

change = 1 

for f, e in iteritems(factors): 

change = change * f**e 

poly = poly * (change ** deg) 

poly = poly(poly.parent().gen() / change) 

return change, poly 

 

def do_polred(poly): 

r""" 

Find a polynomial of reasonably small discriminant that generates 

the same number field as ``poly``, using the PARI ``polredbest`` 

function. 

 

INPUT: 

 

- ``poly`` - a monic irreducible polynomial with integer coefficients. 

 

OUTPUT: 

 

A triple (``elt_fwd``, ``elt_back``, ``new_poly``), where: 

 

- ``new_poly`` is the new polynomial defining the same number field, 

- ``elt_fwd`` is a polynomial expression for a root of the new 

polynomial in terms of a root of the original polynomial, 

- ``elt_back`` is a polynomial expression for a root of the original 

polynomial in terms of a root of the new polynomial. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import do_polred 

sage: R.<x> = QQ['x'] 

sage: oldpol = x^2 - 5 

sage: fwd, back, newpol = do_polred(oldpol) 

sage: newpol 

x^2 - x - 1 

sage: Kold.<a> = NumberField(oldpol) 

sage: Knew.<b> = NumberField(newpol) 

sage: newpol(fwd(a)) 

0 

sage: oldpol(back(b)) 

0 

sage: do_polred(x^2 - x - 11) 

(1/3*x + 1/3, 3*x - 1, x^2 - x - 1) 

sage: do_polred(x^3 + 123456) 

(-1/4*x, -4*x, x^3 - 1929) 

 

This shows that :trac:`13054` has been fixed:: 

 

sage: do_polred(x^4 - 4294967296*x^2 + 54265257667816538374400) 

(1/4*x, 4*x, x^4 - 268435456*x^2 + 211973662764908353025) 

""" 

new_poly, elt_back = poly.__pari__().polredbest(flag=1) 

 

parent = poly.parent() 

elt_fwd = elt_back.modreverse() 

return parent(elt_fwd.lift()), parent(elt_back.lift()), parent(new_poly) 

 

def isolating_interval(intv_fn, pol): 

""" 

``intv_fn`` is a function that takes a precision and returns an 

interval of that precision containing some particular root of pol. 

(It must return better approximations as the precision increases.) 

pol is an irreducible polynomial with rational coefficients. 

 

Returns an interval containing at most one root of pol. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import isolating_interval 

 

sage: _.<x> = QQ['x'] 

sage: isolating_interval(lambda prec: sqrt(RealIntervalField(prec)(2)), x^2 - 2) 

1.4142135623730950488? 

 

And an example that requires more precision:: 

 

sage: delta = 10^(-70) 

sage: p = (x - 1) * (x - 1 - delta) * (x - 1 + delta) 

sage: isolating_interval(lambda prec: RealIntervalField(prec)(1 + delta), p) 

1.000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000? 

 

The function also works with complex intervals and complex roots:: 

 

sage: p = x^2 - x + 13/36 

sage: isolating_interval(lambda prec: ComplexIntervalField(prec)(1/2, 1/3), p) 

0.500000000000000000000? + 0.3333333333333333334?*I 

""" 

dpol = pol.derivative() 

 

for prec in prec_seq(): 

intv = intv_fn(prec) 

ifld = intv.parent() 

 

# We need to verify that pol has exactly one root in the 

# interval intv. We know (because it is a precondition of 

# calling this function) that it has at least one root in the 

# interval, so we only need to verify that it has at most one 

# root (that the interval is sufficiently narrow). 

 

# We do this by computing the derivative of the polynomial 

# over the interval. If the derivative is bounded away from zero, 

# then we know there can be at most one root. 

 

if not dpol(intv).contains_zero(): 

return intv 

 

def find_zero_result(fn, l): 

""" 

``l`` is a list of some sort. ``fn`` is a function which maps an element of 

``l`` and a precision into an interval (either real or complex) of that 

precision, such that for sufficient precision, exactly one element of ``l`` 

results in an interval containing 0. Returns that one element of ``l``. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import find_zero_result 

sage: _.<x> = QQ['x'] 

sage: delta = 10^(-70) 

sage: p1 = x - 1 

sage: p2 = x - 1 - delta 

sage: p3 = x - 1 + delta 

sage: p2 == find_zero_result(lambda p, prec: p(RealIntervalField(prec)(1 + delta)), [p1, p2, p3]) 

True 

""" 

for prec in prec_seq(): 

result = None 

ambig = False 

for v in l: 

intv = fn(v, prec) 

if intv.contains_zero(): 

if result is not None: 

ambig = True 

break 

result = v 

if ambig: 

continue 

if result is None: 

raise ValueError('find_zero_result could not find any zeroes') 

return result 

 

def conjugate_expand(v): 

r""" 

If the interval ``v`` (which may be real or complex) includes some 

purely real numbers, return ``v'`` containing ``v`` such that 

``v' == v'.conjugate()``. Otherwise return ``v`` unchanged. (Note that if 

``v' == v'.conjugate()``, and ``v'`` includes one non-real root of a real 

polynomial, then ``v'`` also includes the conjugate of that root. 

Also note that the diameter of the return value is at most twice 

the diameter of the input.) 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import conjugate_expand 

sage: conjugate_expand(CIF(RIF(0, 1), RIF(1, 2))).str(style='brackets') 

'[0.00000000000000000 .. 1.0000000000000000] + [1.0000000000000000 .. 2.0000000000000000]*I' 

sage: conjugate_expand(CIF(RIF(0, 1), RIF(0, 1))).str(style='brackets') 

'[0.00000000000000000 .. 1.0000000000000000] + [-1.0000000000000000 .. 1.0000000000000000]*I' 

sage: conjugate_expand(CIF(RIF(0, 1), RIF(-2, 1))).str(style='brackets') 

'[0.00000000000000000 .. 1.0000000000000000] + [-2.0000000000000000 .. 2.0000000000000000]*I' 

sage: conjugate_expand(RIF(1, 2)).str(style='brackets') 

'[1.0000000000000000 .. 2.0000000000000000]' 

""" 

if is_RealIntervalFieldElement(v): 

return v 

im = v.imag() 

if not im.contains_zero(): 

return v 

re = v.real() 

fld = ComplexIntervalField(v.prec()) 

return fld(re, im.union(-im)) 

 

def conjugate_shrink(v): 

r""" 

If the interval ``v`` includes some purely real numbers, return 

a real interval containing only those real numbers. Otherwise 

return ``v`` unchanged. 

 

If ``v`` includes exactly one root of a real polynomial, and ``v`` was 

returned by ``conjugate_expand()``, then ``conjugate_shrink(v)`` still 

includes that root, and is a ``RealIntervalFieldElement`` iff the root 

in question is real. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import conjugate_shrink 

sage: conjugate_shrink(RIF(3, 4)).str(style='brackets') 

'[3.0000000000000000 .. 4.0000000000000000]' 

sage: conjugate_shrink(CIF(RIF(1, 2), RIF(1, 2))).str(style='brackets') 

'[1.0000000000000000 .. 2.0000000000000000] + [1.0000000000000000 .. 2.0000000000000000]*I' 

sage: conjugate_shrink(CIF(RIF(1, 2), RIF(0, 1))).str(style='brackets') 

'[1.0000000000000000 .. 2.0000000000000000]' 

sage: conjugate_shrink(CIF(RIF(1, 2), RIF(-1, 2))).str(style='brackets') 

'[1.0000000000000000 .. 2.0000000000000000]' 

""" 

if is_RealIntervalFieldElement(v): 

return v 

im = v.imag() 

if im.contains_zero(): 

return v.real() 

return v 

 

def number_field_elements_from_algebraics(numbers, minimal=False): 

r""" 

Given a sequence of elements of either ``AA`` or ``QQbar`` 

(or a mixture), computes a number field containing all of these 

elements, these elements as members of that number field, and a 

homomorphism from the number field back to ``AA`` or 

``QQbar``. 

 

This may not return the smallest such number field, unless 

``minimal=True`` is specified. 

 

Also, a single number can be passed, rather than a sequence; and 

any values which are not elements of ``AA`` or ``QQbar`` 

will automatically be coerced to ``QQbar`` 

 

This function may be useful for efficiency reasons: doing exact 

computations in the corresponding number field will be faster 

than doing exact computations directly in ``AA`` or ``QQbar``. 

 

EXAMPLES: 

 

We can use this to compute the splitting field of a polynomial. 

(Unfortunately this takes an unreasonably long time for non-toy 

examples.):: 

 

sage: x = polygen(QQ) 

sage: p = x^3 + x^2 + x + 17 

sage: rts = p.roots(ring=QQbar, multiplicities=False) 

sage: splitting = number_field_elements_from_algebraics(rts)[0]; splitting 

Number Field in a with defining polynomial y^6 - 40*y^4 - 22*y^3 + 873*y^2 + 1386*y + 594 

sage: p.roots(ring=splitting) 

[(361/29286*a^5 - 19/3254*a^4 - 14359/29286*a^3 + 401/29286*a^2 + 18183/1627*a + 15930/1627, 1), (49/117144*a^5 - 179/39048*a^4 - 3247/117144*a^3 + 22553/117144*a^2 + 1744/4881*a - 17195/6508, 1), (-1493/117144*a^5 + 407/39048*a^4 + 60683/117144*a^3 - 24157/117144*a^2 - 56293/4881*a - 53033/6508, 1)] 

sage: rt2 = AA(sqrt(2)); rt2 

1.414213562373095? 

sage: rt3 = AA(sqrt(3)); rt3 

1.732050807568878? 

sage: qqI = QQbar.zeta(4); qqI 

I 

sage: z3 = QQbar.zeta(3); z3 

-0.500000000000000? + 0.866025403784439?*I 

sage: rt2b = rt3 + rt2 - rt3; rt2b 

1.414213562373095? 

sage: rt2c = z3 + rt2 - z3; rt2c 

1.414213562373095? + 0.?e-19*I 

 

sage: number_field_elements_from_algebraics(rt2) 

(Number Field in a with defining polynomial y^2 - 2, a, Ring morphism: 

From: Number Field in a with defining polynomial y^2 - 2 

To: Algebraic Real Field 

Defn: a |--> 1.414213562373095?) 

 

sage: number_field_elements_from_algebraics((rt2,rt3)) 

(Number Field in a with defining polynomial y^4 - 4*y^2 + 1, [-a^3 + 3*a, -a^2 + 2], Ring morphism: 

From: Number Field in a with defining polynomial y^4 - 4*y^2 + 1 

To: Algebraic Real Field 

Defn: a |--> 0.5176380902050415?) 

 

We've created ``rt2b`` in such a way that \sage doesn't initially know 

that it's in a degree-2 extension of `\QQ`:: 

 

sage: number_field_elements_from_algebraics(rt2b) 

(Number Field in a with defining polynomial y^4 - 4*y^2 + 1, -a^3 + 3*a, Ring morphism: 

From: Number Field in a with defining polynomial y^4 - 4*y^2 + 1 

To: Algebraic Real Field 

Defn: a |--> 0.5176380902050415?) 

 

We can specify ``minimal=True`` if we want the smallest number field:: 

 

sage: number_field_elements_from_algebraics(rt2b, minimal=True) 

(Number Field in a with defining polynomial y^2 - 2, a, Ring morphism: 

From: Number Field in a with defining polynomial y^2 - 2 

To: Algebraic Real Field 

Defn: a |--> 1.414213562373095?) 

 

Things work fine with rational numbers, too:: 

 

sage: number_field_elements_from_algebraics((QQbar(1/2), AA(17))) 

(Rational Field, [1/2, 17], Ring morphism: 

From: Rational Field 

To: Algebraic Real Field 

Defn: 1 |--> 1) 

 

Or we can just pass in symbolic expressions, as long as they can be 

coerced into ``QQbar``:: 

 

sage: number_field_elements_from_algebraics((sqrt(7), sqrt(9), sqrt(11))) 

(Number Field in a with defining polynomial y^4 - 9*y^2 + 1, [-a^3 + 8*a, 3, -a^3 + 10*a], Ring morphism: 

From: Number Field in a with defining polynomial y^4 - 9*y^2 + 1 

To: Algebraic Real Field 

Defn: a |--> 0.3354367396454047?) 

 

Here we see an example of doing some computations with number field 

elements, and then mapping them back into ``QQbar``:: 

 

sage: (fld,nums,hom) = number_field_elements_from_algebraics((rt2, rt3, qqI, z3)) 

sage: fld,nums,hom # random 

(Number Field in a with defining polynomial y^8 - y^4 + 1, [-a^5 + a^3 + a, a^6 - 2*a^2, a^6, -a^4], Ring morphism: 

From: Number Field in a with defining polynomial y^8 - y^4 + 1 

To: Algebraic Field 

Defn: a |--> -0.2588190451025208? - 0.9659258262890683?*I) 

sage: (nfrt2, nfrt3, nfI, nfz3) = nums 

sage: hom(nfrt2) 

1.414213562373095? + 0.?e-18*I 

sage: nfrt2^2 

2 

sage: nfrt3^2 

3 

sage: nfz3 + nfz3^2 

-1 

sage: nfI^2 

-1 

sage: sum = nfrt2 + nfrt3 + nfI + nfz3; sum 

2*a^6 + a^5 - a^4 - a^3 - 2*a^2 - a 

sage: hom(sum) 

2.646264369941973? + 1.866025403784439?*I 

sage: hom(sum) == rt2 + rt3 + qqI + z3 

True 

sage: [hom(n) for n in nums] == [rt2, rt3, qqI, z3] 

True 

 

TESTS:: 

 

sage: number_field_elements_from_algebraics(rt3) 

(Number Field in a with defining polynomial y^2 - 3, a, Ring morphism: 

From: Number Field in a with defining polynomial y^2 - 3 

To: Algebraic Real Field 

Defn: a |--> 1.732050807568878?) 

sage: number_field_elements_from_algebraics((rt2,qqI)) 

(Number Field in a with defining polynomial y^4 + 1, [-a^3 + a, a^2], Ring morphism: 

From: Number Field in a with defining polynomial y^4 + 1 

To: Algebraic Field 

Defn: a |--> 0.7071067811865475? + 0.7071067811865475?*I) 

 

Note that for the first example, where \sage doesn't realize that 

the number is real, we get a homomorphism to ``QQbar``; but with 

``minimal=True``, we get a homomorphism to ``AA``. Also note 

that the exact answer depends on a Pari function that gives 

different answers for 32-bit and 64-bit machines:: 

 

sage: number_field_elements_from_algebraics(rt2c) 

(Number Field in a with defining polynomial y^4 + 2*y^2 + 4, 1/2*a^3, Ring morphism: 

From: Number Field in a with defining polynomial y^4 + 2*y^2 + 4 

To: Algebraic Field 

Defn: a |--> -0.7071067811865475? - 1.224744871391589?*I) 

sage: number_field_elements_from_algebraics(rt2c, minimal=True) 

(Number Field in a with defining polynomial y^2 - 2, a, Ring morphism: 

From: Number Field in a with defining polynomial y^2 - 2 

To: Algebraic Real Field 

Defn: a |--> 1.414213562373095?) 

 

""" 

gen = qq_generator 

 

# Keep track of whether we were given a single value or a list. 

single_number = False 

try: 

len(numbers) 

except TypeError: 

numbers = [numbers] 

single_number = True 

 

def mk_algebraic(x): 

if isinstance(x, AlgebraicNumber_base): 

return x 

return QQbar(x) 

 

numbers = [mk_algebraic(_) for _ in numbers] 

 

for v in numbers: 

if minimal: 

v.simplify() 

gen = gen.union(v._exact_field()) 

 

fld = gen._field 

 

nums = [gen(v._exact_value()) for v in numbers] 

 

if single_number: 

nums = nums[0] 

 

hom = fld.hom([gen.root_as_algebraic()]) 

 

return (fld, nums, hom) 

 

# Cache some commonly-used polynomial rings 

QQx = QQ['x'] 

QQx_x = QQx.gen() 

QQy = QQ['y'] 

QQy_y = QQy.gen() 

QQxy = QQ['x', 'y'] 

QQxy_x = QQxy.gen(0) 

QQxy_y = QQxy.gen(1) 

 

 

def cmp_elements_with_same_minpoly(a, b, p): 

r""" 

Compare the algebraic elements ``a`` and ``b`` knowing that they have the 

same minimal polynomial ``p``. 

 

This is an helper function for comparison of algebraic elements (i.e. the 

methods :meth:`AlgebraicNumber._richcmp_` and 

:meth:`AlgebraicReal._richcmp_`). 

 

INPUT: 

 

- ``a`` and ``b`` -- elements of the algebraic or the real algebraic field 

with same minimal polynomial 

 

- ``p`` -- the minimal polynomial 

 

OUTPUT: 

 

`-1`, `0`, `1`, `None` depending on whether `a < b`, `a = b` or `a > b` or 

the function did not succeed with the given precision of `a` and `b`. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import cmp_elements_with_same_minpoly 

sage: x = polygen(ZZ) 

sage: p = x^2 - 2 

sage: a = AA.polynomial_root(p, RIF(1,2)) 

sage: b = AA.polynomial_root(p, RIF(-2,-1)) 

sage: cmp_elements_with_same_minpoly(a, b, p) 

1 

sage: cmp_elements_with_same_minpoly(-a, b, p) 

0 

""" 

ar = a._value.real() 

br = b._value.real() 

if not ar.overlaps(br): 

return -1 if (ar < br) else 1 

 

ai = a._value.imag() 

bi = b._value.imag() 

 

if a.parent() is AA or b.parent() is AA: 

ring = AA 

else: 

ring = QQbar 

roots = p.roots(ring, False) 

 

real = ar.union(br) 

imag = ai.union(bi) 

roots = [r for r in roots if r._value.real().overlaps(real) 

and r._value.imag().abs().overlaps(imag)] 

if len(roots) == 1: 

# There is only a single (real) root matching both descriptors 

# so they both must be that root and therefore equal. 

return 0 

if (len(roots) == 2 and 

not roots[0]._value.imag().contains_zero()): 

# There is a complex conjugate pair of roots matching both 

# descriptors, so compare by imaginary value. 

while ai.contains_zero(): 

a._more_precision() 

ai = a._value.imag() 

while bi.contains_zero(): 

b._more_precision() 

bi = b._value.imag() 

if ai.overlaps(bi): 

return 0 

return -1 if (ai < bi) else 1 

 

return None 

 

 

class AlgebraicGeneratorRelation(SageObject): 

""" 

A simple class for maintaining relations in the lattice of algebraic 

extensions. 

""" 

def __init__(self, child1, child1_poly, child2, child2_poly, parent): 

r""" 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import AlgebraicGeneratorRelation 

sage: AlgebraicGeneratorRelation(None, None, None, None, None) 

<sage.rings.qqbar.AlgebraicGeneratorRelation object at ...> 

""" 

self.child1 = child1 

self.child1_poly = child1_poly 

self.child2 = child2 

self.child2_poly = child2_poly 

self.parent = parent 

 

algebraic_generator_counter = 0 

 

 

@richcmp_method 

class AlgebraicGenerator(SageObject): 

r""" 

An ``AlgebraicGenerator`` represents both an algebraic number `\alpha` and 

the number field `\QQ[\alpha]`. There is a single ``AlgebraicGenerator`` 

representing `\QQ` (with `\alpha=0`). 

 

The ``AlgebraicGenerator`` class is private, and should not be used 

directly. 

""" 

 

def __init__(self, field, root): 

""" 

Construct an ``AlgebraicGenerator`` object. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import ANRoot, AlgebraicGenerator, qq_generator 

sage: y = polygen(QQ, 'y') 

sage: x = polygen(QQbar) 

sage: nf = NumberField(y^2 - y - 1, name='a', check=False) 

sage: root = ANRoot(x^2 - x - 1, RIF(1, 2)) 

sage: gen = AlgebraicGenerator(nf, root) 

sage: gen 

Number Field in a with defining polynomial y^2 - y - 1 with a in 1.618033988749895? 

sage: gen.field() 

Number Field in a with defining polynomial y^2 - y - 1 

sage: gen.is_trivial() 

False 

sage: gen.union(qq_generator) is gen 

True 

sage: qq_generator.union(gen) is gen 

True 

sage: nf = NumberField(y^2 + 1, name='a', check=False) 

sage: root = ANRoot(x^2 + 1, CIF(0, 1)) 

sage: x = AlgebraicGenerator(nf, root); x 

Number Field in a with defining polynomial y^2 + 1 with a in 1*I 

""" 

self._field = field 

self._pari_field = None 

self._trivial = (field is QQ) 

self._root = root 

self._root_as_algebraic = (QQbar if root.is_complex() else AA)(root) 

self._unions = {} 

self._cyclotomic = False 

global algebraic_generator_counter 

self._index = algebraic_generator_counter 

algebraic_generator_counter += 1 

 

def __reduce__(self): 

""" 

Add customized pickling support. 

 

EXAMPLES:: 

 

sage: t = QQbar(sqrt(2)) + QQbar(sqrt(3)) 

sage: t.exactify() 

sage: type(t._descr._generator) 

<class 'sage.rings.qqbar.AlgebraicGenerator'> 

sage: loads(dumps(t)) == t 

True 

""" 

return (AlgebraicGenerator, (self._field, self._root)) 

 

def __hash__(self): 

r""" 

Return a hash value for self. This will depend on the order that 

commands get executed at load time, so we do not test the value that is 

returned, just that it doesn't raise an error. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import ANRoot, AlgebraicGenerator, qq_generator 

sage: _.<y> = QQ['y'] 

sage: x = polygen(QQbar) 

sage: nf = NumberField(y^2 - y - 1, name='a', check=False) 

sage: root = ANRoot(x^2 - x - 1, RIF(1, 2)) 

sage: gen = AlgebraicGenerator(nf, root) 

sage: hash(gen) # random 

""" 

return self._index 

 

def __richcmp__(self, other, op): 

r""" 

Compare ``self`` with another ``AlgebraicGenerator`` object. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import ANRoot, AlgebraicGenerator, qq_generator 

sage: _.<y> = QQ['y'] 

sage: x = polygen(QQbar) 

sage: nf = NumberField(y^2 - y - 1, name='a', check=False) 

sage: root = ANRoot(x^2 - x - 1, RIF(1, 2)) 

sage: gen = AlgebraicGenerator(nf, root) 

sage: gen > qq_generator 

True 

""" 

return richcmp(self._index, other._index, op) 

 

def is_complex(self): 

r""" 

Return True if this is a generator for a non-real number field. 

 

EXAMPLES:: 

 

sage: z7 = QQbar.zeta(7) 

sage: g = z7._descr._generator 

sage: g.is_complex() 

True 

 

sage: from sage.rings.qqbar import ANRoot, AlgebraicGenerator 

sage: y = polygen(QQ, 'y') 

sage: x = polygen(QQbar) 

sage: nf = NumberField(y^2 - y - 1, name='a', check=False) 

sage: root = ANRoot(x^2 - x - 1, RIF(1, 2)) 

sage: gen = AlgebraicGenerator(nf, root) 

sage: gen.is_complex() 

False 

""" 

return self._root.is_complex() 

 

def _repr_(self): 

r""" 

String representation of self. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import qq_generator 

sage: qq_generator._repr_() 

'Trivial generator' 

 

sage: from sage.rings.qqbar import ANRoot, AlgebraicGenerator, qq_generator 

sage: y = polygen(QQ) 

sage: x = polygen(QQbar) 

sage: nf = NumberField(y^2 - y - 1, name='a', check=False) 

sage: root = ANRoot(x^2 - x - 1, RIF(1, 2)) 

sage: gen = AlgebraicGenerator(nf, root) 

sage: gen._repr_() 

'Number Field in a with defining polynomial x^2 - x - 1 with a in 1.618033988749895?' 

""" 

if self._trivial: 

return 'Trivial generator' 

else: 

return '%s with a in %s'%(self._field, self._root._interval_fast(53)) 

 

def root_as_algebraic(self): 

r""" 

Return the root attached to self as an algebraic number. 

 

EXAMPLES:: 

 

sage: t = sage.rings.qqbar.qq_generator.root_as_algebraic(); t 

1 

sage: t.parent() 

Algebraic Real Field 

""" 

return self._root_as_algebraic 

 

def is_trivial(self): 

""" 

Returns true iff this is the trivial generator (alpha == 1), which 

does not actually extend the rationals. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import qq_generator 

sage: qq_generator.is_trivial() 

True 

""" 

return self._trivial 

 

def field(self): 

r""" 

Return the number field attached to self. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import qq_generator 

sage: qq_generator.field() 

Rational Field 

""" 

return self._field 

 

def pari_field(self): 

r""" 

Return the PARI field attached to this generator. 

 

EXAMPLES:: 

 

 

sage: from sage.rings.qqbar import qq_generator 

sage: qq_generator.pari_field() 

Traceback (most recent call last): 

... 

ValueError: No PARI field attached to trivial generator 

 

sage: from sage.rings.qqbar import ANRoot, AlgebraicGenerator, qq_generator 

sage: y = polygen(QQ) 

sage: x = polygen(QQbar) 

sage: nf = NumberField(y^2 - y - 1, name='a', check=False) 

sage: root = ANRoot(x^2 - x - 1, RIF(1, 2)) 

sage: gen = AlgebraicGenerator(nf, root) 

sage: gen.pari_field() 

[y^2 - y - 1, [2, 0], ...] 

""" 

if self.is_trivial(): raise ValueError("No PARI field attached to trivial generator") 

if self._pari_field is None: 

pari_pol = self._field.pari_polynomial("y") 

self._pari_field = pari_pol.nfinit(1) 

return self._pari_field 

 

def conjugate(self): 

r""" 

If this generator is for the algebraic number `\alpha`, return a 

generator for the complex conjugate of `\alpha`. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import AlgebraicGenerator 

sage: x = polygen(QQ); f = x^4 + x + 17 

sage: nf = NumberField(f,name='a') 

sage: b = f.roots(QQbar)[0][0] 

sage: root = b._descr 

sage: gen = AlgebraicGenerator(nf, root) 

sage: gen.conjugate() 

Number Field in a with defining polynomial x^4 + x + 17 with a in -1.436449997483091? + 1.374535713065812?*I 

""" 

try: 

return self._conjugate 

except AttributeError: 

if not self.is_complex(): 

self._conjugate = self 

else: 

conj = AlgebraicGenerator(self._field, self._root.conjugate(None)) 

self._conjugate = conj 

conj._conjugate = self 

if self._cyclotomic: 

conj_rel = QQx_x ** (self._cyclotomic_order - 1) 

rel = AlgebraicGeneratorRelation(self, conj_rel, conj, conj_rel, self) 

self._unions[conj] = rel 

conj._unions[self] = rel 

return self._conjugate 

 

def _interval_fast(self, prec): 

""" 

Returns an interval containing this generator, to the specified 

precision. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import ANRoot, AlgebraicGenerator, qq_generator 

sage: y = polygen(QQ, 'y') 

sage: x = polygen(QQbar) 

sage: nf = NumberField(y^2 - y - 1, name='a', check=False) 

sage: root = ANRoot(x^2 - x - 1, RIF(1, 2)) 

sage: gen = AlgebraicGenerator(nf, root) 

sage: gen._interval_fast(128) 

1.61803398874989484820458683436563811773? 

""" 

return self._root._interval_fast(prec) 

 

def union(self, other): 

r""" Given generators ``alpha`` and ``beta``, 

``alpha.union(beta)`` gives a generator for the number field 

`\QQ[\alpha][\beta]`. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import ANRoot, AlgebraicGenerator, qq_generator 

sage: _.<y> = QQ['y'] 

sage: x = polygen(QQbar) 

sage: nf2 = NumberField(y^2 - 2, name='a', check=False) 

sage: root2 = ANRoot(x^2 - 2, RIF(1, 2)) 

sage: gen2 = AlgebraicGenerator(nf2, root2) 

sage: gen2 

Number Field in a with defining polynomial y^2 - 2 with a in 1.414213562373095? 

sage: nf3 = NumberField(y^2 - 3, name='a', check=False) 

sage: root3 = ANRoot(x^2 - 3, RIF(1, 2)) 

sage: gen3 = AlgebraicGenerator(nf3, root3) 

sage: gen3 

Number Field in a with defining polynomial y^2 - 3 with a in 1.732050807568878? 

sage: gen2.union(qq_generator) is gen2 

True 

sage: qq_generator.union(gen3) is gen3 

True 

sage: gen2.union(gen3) 

Number Field in a with defining polynomial y^4 - 4*y^2 + 1 with a in 0.5176380902050415? 

""" 

if self._trivial: 

return other 

if other._trivial: 

return self 

if self is other: 

return self 

if other in self._unions: 

return self._unions[other].parent 

if self._field.polynomial().degree() < other._field.polynomial().degree(): 

self, other = other, self 

elif other._cyclotomic: 

self, other = other, self 

 

sp = self._field.polynomial() 

op = other._field.polynomial() 

op = QQx(op) 

# pari_nf = self._field.pari_nf() 

pari_nf = self.pari_field() 

factors = list(pari_nf.nffactor(op).lift())[0] 

x, y = QQxy.gens() 

factors_sage = [QQxy(p) for p in factors] 

 

def find_fn(p, prec): 

ifield = RealIntervalField(prec) 

if_poly = ifield['x', 'y'] 

ip = if_poly(p) 

return ip(other._root._interval_fast(prec), self._root._interval_fast(prec)) 

my_factor = find_zero_result(find_fn, factors_sage) 

 

if my_factor.degree(x) == 1 and my_factor.coefficient(x) == 1: 

value = (-my_factor + x).univariate_polynomial(QQy) 

rel = AlgebraicGeneratorRelation(self, QQy_y, 

other, value, 

self) 

self._unions[other] = rel 

other._unions[self] = rel 

return rel.parent 

 

# XXX need more caching here 

newpol, self_pol, k = pari_nf.rnfequation(my_factor, 1) 

k = int(k) 

 

newpol_sage = QQx(newpol) 

newpol_sage_y = QQy(newpol_sage) 

 

red_elt, red_back, red_pol = do_polred(newpol_sage_y) 

 

red_back_x = QQx(red_back) 

 

new_nf = NumberField(red_pol, name='a', check=False) 

 

self_pol_sage = QQx(self_pol.lift()) 

 

new_nf_a = new_nf.gen() 

 

def intv_fn(prec): 

return conjugate_expand(red_elt(self._root._interval_fast(prec) * k + other._root._interval_fast(prec))) 

new_intv = conjugate_shrink(isolating_interval(intv_fn, red_pol)) 

 

new_gen = AlgebraicGenerator(new_nf, ANRoot(QQx(red_pol), new_intv)) 

rel = AlgebraicGeneratorRelation(self, self_pol_sage(red_back_x), 

other, (QQx_x - k*self_pol_sage)(red_back_x), 

new_gen) 

self._unions[other] = rel 

other._unions[self] = rel 

return new_gen 

 

def super_poly(self, super, checked=None): 

r""" 

Given a generator ``gen`` and another generator ``super``, where ``super`` 

is the result of a tree of ``union()`` operations where one of the 

leaves is ``gen``, ``gen.super_poly(super)`` returns a polynomial 

expressing the value of ``gen`` in terms of the value of ``super`` 

(except that if ``gen`` is ``qq_generator``, ``super_poly()`` always 

returns None.) 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import AlgebraicGenerator, ANRoot, qq_generator 

sage: _.<y> = QQ['y'] 

sage: x = polygen(QQbar) 

sage: nf2 = NumberField(y^2 - 2, name='a', check=False) 

sage: root2 = ANRoot(x^2 - 2, RIF(1, 2)) 

sage: gen2 = AlgebraicGenerator(nf2, root2) 

sage: gen2 

Number Field in a with defining polynomial y^2 - 2 with a in 1.414213562373095? 

sage: nf3 = NumberField(y^2 - 3, name='a', check=False) 

sage: root3 = ANRoot(x^2 - 3, RIF(1, 2)) 

sage: gen3 = AlgebraicGenerator(nf3, root3) 

sage: gen3 

Number Field in a with defining polynomial y^2 - 3 with a in 1.732050807568878? 

sage: gen2_3 = gen2.union(gen3) 

sage: gen2_3 

Number Field in a with defining polynomial y^4 - 4*y^2 + 1 with a in 0.5176380902050415? 

sage: qq_generator.super_poly(gen2) is None 

True 

sage: gen2.super_poly(gen2_3) 

-a^3 + 3*a 

sage: gen3.super_poly(gen2_3) 

-a^2 + 2 

 

""" 

if checked is None: 

checked = {} 

checked[self] = True 

if super is self: 

return self._field.gen() 

for u in self._unions.values(): 

if u.parent in checked: 

continue 

poly = u.parent.super_poly(super, checked) 

if poly is None: 

continue 

if self is u.child1: 

return u.child1_poly(poly) 

assert(self is u.child2) 

return u.child2_poly(poly) 

return None 

 

def __call__(self, elt): 

""" 

Takes an algebraic number which is represented as either a 

rational or a number field element, and which is in a subfield 

of the field generated by this generator. Lifts the number 

into the field of this generator, and returns either a 

``Rational`` or a ``NumberFieldElement`` depending on whether 

this is the trivial generator. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import ANRoot, AlgebraicGenerator, ANExtensionElement, ANRational 

sage: _.<y> = QQ['y'] 

sage: x = polygen(QQbar) 

sage: nf2 = NumberField(y^2 - 2, name='a', check=False) 

sage: root2 = ANRoot(x^2 - 2, RIF(1, 2)) 

sage: gen2 = AlgebraicGenerator(nf2, root2) 

sage: gen2 

Number Field in a with defining polynomial y^2 - 2 with a in 1.414213562373095? 

sage: sqrt2 = ANExtensionElement(gen2, nf2.gen()) 

sage: nf3 = NumberField(y^2 - 3, name='a', check=False) 

sage: root3 = ANRoot(x^2 - 3, RIF(1, 2)) 

sage: gen3 = AlgebraicGenerator(nf3, root3) 

sage: gen3 

Number Field in a with defining polynomial y^2 - 3 with a in 1.732050807568878? 

sage: sqrt3 = ANExtensionElement(gen3, nf3.gen()) 

sage: gen2_3 = gen2.union(gen3) 

sage: gen2_3 

Number Field in a with defining polynomial y^4 - 4*y^2 + 1 with a in 0.5176380902050415? 

sage: gen2_3(sqrt2) 

-a^3 + 3*a 

sage: gen2_3(ANRational(1/7)) 

1/7 

sage: gen2_3(sqrt3) 

-a^2 + 2 

""" 

if self._trivial: 

return elt._value 

if isinstance(elt, ANRational): 

return self._field(elt._value) 

if elt.generator() is self: 

return elt.field_element_value() 

gen = elt.generator() 

sp = gen.super_poly(self) 

assert(not(sp is None)) 

return self._field(elt.field_element_value().polynomial()(sp)) 

 

 

# dictionary for multimethod dispatch 

_binop_algo = {} 

 

class ANDescr(SageObject): 

r""" 

An ``AlgebraicNumber`` or ``AlgebraicReal`` is a wrapper around an 

``ANDescr`` object. ``ANDescr`` is an abstract base class, which should 

never be directly instantiated; its concrete subclasses are ``ANRational``, 

``ANBinaryExpr``, ``ANUnaryExpr``, ``ANRoot``, and ``ANExtensionElement``. 

``ANDescr`` and all of its subclasses are for internal use, and should not 

be used directly. 

""" 

def is_simple(self): 

r""" 

Checks whether this descriptor represents a value with the same 

algebraic degree as the number field associated with the descriptor. 

 

Returns ``True`` if self is an ``ANRational``, or a minimal 

``ANExtensionElement``. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import ANRational 

sage: ANRational(1/2).is_simple() 

True 

sage: rt2 = AA(sqrt(2)) 

sage: rt3 = AA(sqrt(3)) 

sage: rt2b = rt3 + rt2 - rt3 

sage: rt2.exactify() 

sage: rt2._descr.is_simple() 

True 

sage: rt2b.exactify() 

sage: rt2b._descr.is_simple() 

False 

sage: rt2b.simplify() 

sage: rt2b._descr.is_simple() 

True 

""" 

return False 

 

# Unitary operators: the second argument "n" is an AlgebraicNumber_base 

# wrapper around self. 

 

def neg(self, n): 

r""" 

Negation of self. 

 

EXAMPLES:: 

 

sage: a = QQbar(sqrt(2)) 

sage: b = a._descr 

sage: b.neg(a) 

<sage.rings.qqbar.ANUnaryExpr object at ...> 

""" 

return ANUnaryExpr(n, '-') 

 

def invert(self, n): 

r""" 

1/self. 

 

EXAMPLES:: 

 

sage: a = QQbar(sqrt(2)) 

sage: b = a._descr 

sage: b.invert(a) 

<sage.rings.qqbar.ANUnaryExpr object at ...> 

""" 

return ANUnaryExpr(n, '~') 

 

def abs(self, n): 

r""" 

Absolute value of self. 

 

EXAMPLES:: 

 

sage: a = QQbar(sqrt(2)) 

sage: b = a._descr 

sage: b.abs(a) 

<sage.rings.qqbar.ANUnaryExpr object at ...> 

""" 

return ANUnaryExpr(n, 'abs') 

 

def real(self, n): 

r""" 

Real part of self. 

 

EXAMPLES:: 

 

sage: a = QQbar(sqrt(-7)) 

sage: b = a._descr 

sage: b.real(a) 

<sage.rings.qqbar.ANUnaryExpr object at ...> 

""" 

if self.is_complex(): 

return ANUnaryExpr(n, 'real') 

else: 

return self 

 

def imag(self, n): 

r""" 

Imaginary part of self. 

 

EXAMPLES:: 

 

sage: a = QQbar(sqrt(-7)) 

sage: b = a._descr 

sage: b.imag(a) 

<sage.rings.qqbar.ANUnaryExpr object at ...> 

""" 

if self.is_complex(): 

return ANUnaryExpr(n, 'imag') 

else: 

return ANRational(0) 

 

def conjugate(self, n): 

r""" 

Complex conjugate of self. 

 

EXAMPLES:: 

 

sage: a = QQbar(sqrt(-7)) 

sage: b = a._descr 

sage: b.conjugate(a) 

<sage.rings.qqbar.ANUnaryExpr object at ...> 

""" 

if self.is_complex(): 

return ANUnaryExpr(n, 'conjugate') 

else: 

return self 

 

def norm(self, n): 

r""" 

Field norm of self from `\overline{\QQ}` to its real subfield 

`\mathbf{A}`, i.e.~the square of the usual complex absolute value. 

 

EXAMPLES:: 

 

sage: a = QQbar(sqrt(-7)) 

sage: b = a._descr 

sage: b.norm(a) 

<sage.rings.qqbar.ANUnaryExpr object at ...> 

""" 

if self.is_complex(): 

return ANUnaryExpr(n, 'norm') 

else: 

return (n*n)._descr 

 

 

class AlgebraicNumber_base(sage.structure.element.FieldElement): 

r""" 

This is the common base class for algebraic numbers (complex 

numbers which are the zero of a polynomial in `\ZZ[x]`) and algebraic 

reals (algebraic numbers which happen to be real). 

 

``AlgebraicNumber`` objects can be created using ``QQbar`` (== 

``AlgebraicNumberField()``), and ``AlgebraicReal`` objects can be created 

using ``AA`` (== ``AlgebraicRealField()``). They can be created either by 

coercing a rational or a symbolic expression, or by using the 

``QQbar.polynomial_root()`` or ``AA.polynomial_root()`` method to 

construct a particular root of a polynomial with algebraic 

coefficients. Also, ``AlgebraicNumber`` and ``AlgebraicReal`` are closed 

under addition, subtraction, multiplication, division (except by 

0), and rational powers (including roots), except that for a 

negative ``AlgebraicReal``, taking a power with an even denominator returns 

an ``AlgebraicNumber`` instead of an ``AlgebraicReal``. 

 

``AlgebraicNumber`` and ``AlgebraicReal`` objects can be 

approximated to any desired precision. They can be compared 

exactly; if the two numbers are very close, or are equal, this may 

require exact computation, which can be extremely slow. 

 

As long as exact computation is not triggered, computation with 

algebraic numbers should not be too much slower than computation with 

intervals. As mentioned above, exact computation is triggered 

when comparing two algebraic numbers which are very close together. 

This can be an explicit comparison in user code, but the following 

list of actions (not necessarily complete) can also trigger exact 

computation: 

 

- Dividing by an algebraic number which is very close to 0. 

 

- Using an algebraic number which is very close to 0 as the leading 

coefficient in a polynomial. 

 

- Taking a root of an algebraic number which is very close to 0. 

 

The exact definition of "very close" is subject to change; currently, 

we compute our best approximation of the two numbers using 128-bit 

arithmetic, and see if that's sufficient to decide the comparison. 

Note that comparing two algebraic numbers which are actually equal will 

always trigger exact computation, unless they are actually the same object. 

 

EXAMPLES:: 

 

sage: sqrt(QQbar(2)) 

1.414213562373095? 

sage: sqrt(QQbar(2))^2 == 2 

True 

sage: x = polygen(QQbar) 

sage: phi = QQbar.polynomial_root(x^2 - x - 1, RIF(1, 2)) 

sage: phi 

1.618033988749895? 

sage: phi^2 == phi+1 

True 

sage: AA(sqrt(65537)) 

256.0019531175495? 

""" 

 

def __init__(self, parent, x): 

r""" 

Initialize an algebraic number. The argument must be either 

a rational number, a Gaussian rational, or a subclass of ``ANDescr``. 

 

EXAMPLES:: 

 

sage: AlgebraicReal(22/7) 

22/7 

""" 

sage.structure.element.FieldElement.__init__(self, parent) 

if isinstance(x, integer_types + (sage.rings.integer.Integer, 

sage.rings.rational.Rational)): 

self._descr = ANRational(x) 

elif isinstance(x, ANDescr): 

self._descr = x 

elif parent is QQbar and \ 

isinstance(x, NumberFieldElement_quadratic) and \ 

list(x.parent().polynomial()) == [1, 0, 1]: 

self._descr = ANExtensionElement(QQbar_I_generator, QQbar_I_nf(x.list())) 

else: 

raise TypeError("Illegal initializer for algebraic number") 

 

self._value = self._descr._interval_fast(64) 

 

def _repr_(self): 

""" 

Returns the print representation of this number. 

 

EXAMPLES:: 

 

sage: AA(22/7) # indirect doctest 

22/7 

sage: QQbar(1/3 + 2/7*I) 

2/7*I + 1/3 

sage: QQbar.zeta(4) + 5 

I + 5 

sage: QQbar.zeta(4) 

I 

sage: 3*QQbar.zeta(4) 

3*I 

sage: QQbar.zeta(17) 

0.9324722294043558? + 0.3612416661871530?*I 

sage: AA(19).sqrt() 

4.358898943540674? 

""" 

if isinstance(self._descr, ANRational): 

return repr(self._descr) 

if isinstance(self._descr, ANExtensionElement) and self._descr._generator is QQbar_I_generator: 

return repr(self._descr._value) 

if self.parent() is QQbar: 

return repr(CIF(self._value)) 

else: 

return repr(RIF(self._value)) 

 

def _latex_(self): 

r""" 

Returns the latex representation of this number. 

 

EXAMPLES:: 

 

sage: latex(AA(22/7)) 

\frac{22}{7} 

sage: latex(QQbar(1/3 + 2/7*I)) 

\frac{2}{7} i + \frac{1}{3} 

sage: latex(QQbar.zeta(4) + 5) 

i + 5 

sage: latex(QQbar.zeta(4)) 

i 

sage: latex(3*QQbar.zeta(4)) 

3 i 

sage: latex(QQbar.zeta(17)) 

0.9324722294043558? + 0.3612416661871530? \sqrt{-1} 

sage: latex(AA(19).sqrt()) 

4.358898943540674? 

""" 

from sage.misc.latex import latex 

if isinstance(self._descr, ANRational): 

return latex(self._descr._value) 

if isinstance(self._descr, ANExtensionElement) and self._descr._generator is QQbar_I_generator: 

return latex(self._descr._value) 

return repr(self).replace('*I', r' \sqrt{-1}') 

 

def _sage_input_(self, sib, coerce): 

r""" 

Produce an expression which will reproduce this value when evaluated. 

 

EXAMPLES: 

 

These examples are mostly copied from the doctests of 

the ``handle_sage_input`` functions; see those for more examples:: 

 

sage: sage_input(QQbar(3)) 

QQbar(3) 

sage: sage_input(AA(22/7)) 

AA(22/7) 

sage: sage_input(22/7*QQbar.zeta(4)) 

QQbar(22/7*I) 

sage: sage_input(QQbar.zeta(5)^3) 

R.<x> = AA[] 

QQbar.polynomial_root(AA.common_polynomial(x^4 + x^3 + x^2 + x + 1), CIF(RIF(RR(0.3090169943749474), RR(0.30901699437494745)), RIF(RR(0.95105651629515353), RR(0.95105651629515364))))^3 

sage: sage_input((AA(3)^(1/2))^(1/3)) 

R.<x> = AA[] 

AA.polynomial_root(AA.common_polynomial(x^3 - AA.polynomial_root(AA.common_polynomial(x^2 - 3), RIF(RR(1.7320508075688772), RR(1.7320508075688774)))), RIF(RR(1.2009369551760025), RR(1.2009369551760027))) 

sage: sage_input(QQbar(3+4*I)) 

QQbar(3 + 4*I) 

sage: sage_input(-sqrt(AA(2))) 

R.<x> = AA[] 

-AA.polynomial_root(AA.common_polynomial(x^2 - 2), RIF(RR(1.4142135623730949), RR(1.4142135623730951))) 

sage: sage_input(2 + sqrt(AA(2))) 

R.<x> = AA[] 

2 + AA.polynomial_root(AA.common_polynomial(x^2 - 2), RIF(RR(1.4142135623730949), RR(1.4142135623730951))) 

 

And a nice big example:: 

 

sage: K.<x> = QQ[] 

sage: p = K.random_element(4); p 

1/2*x^4 - 1/95*x^3 - 1/2*x^2 - 4 

sage: rts = p.roots(ring=QQbar, multiplicities=False); rts 

[-1.830225346898784?, 1.842584249981426?, 0.004346864248152390? - 1.540200655088741?*I, 0.004346864248152390? + 1.540200655088741?*I] 

sage: sage_input(rts, verify=True) # long time (2s on sage.math, 2013) 

# Verified 

R.<x> = AA[] 

cp = AA.common_polynomial(1/2*x^4 - 1/95*x^3 - 1/2*x^2 - 4) 

[QQbar.polynomial_root(cp, CIF(RIF(-RR(1.8302253468987832), -RR(1.830225346898783)), RIF(RR(0)))), QQbar.polynomial_root(cp, CIF(RIF(RR(1.8425842499814258), RR(1.842584249981426)), RIF(RR(0)))), QQbar.polynomial_root(cp, CIF(RIF(RR(0.0043468642481523899), RR(0.0043468642481523908)), RIF(-RR(1.5402006550887404), -RR(1.5402006550887402)))), QQbar.polynomial_root(cp, CIF(RIF(RR(0.0043468642481523899), RR(0.0043468642481523908)), RIF(RR(1.5402006550887402), RR(1.5402006550887404))))] 

 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: sqrt(QQbar(7))._sage_input_(sib, False) 

{call: {getattr: {atomic:QQbar}.polynomial_root}({call: {getattr: {atomic:AA}.common_polynomial}({binop:- {binop:** {gen:x {constr_parent: {subscr: {atomic:QQbar}[{atomic:'x'}]} with gens: ('x',)}} {atomic:2}} {atomic:7}})}, {call: {atomic:CIF}({call: {atomic:RIF}({call: {atomic:RR}({atomic:2.6457513110645903})}, {call: {atomic:RR}({atomic:2.6457513110645907})})}, {call: {atomic:RIF}({call: {atomic:RR}({atomic:0})})})})} 

""" 

(v, complicated) = \ 

self._descr.handle_sage_input(sib, coerce, self.parent() is QQbar) 

if complicated or True: 

sib.id_cache(self, v, 'v') 

return v 

 

def _mul_(self, other): 

""" 

TESTS:: 

 

sage: AA(sqrt(2)) * AA(sqrt(8)) # indirect doctest 

4.000000000000000? 

""" 

sk = type(self._descr) 

ok = type(other._descr) 

return type(self)(_binop_algo[sk,ok](self, other, operator.mul)) 

 

def _div_(self, other): 

""" 

TESTS:: 

 

sage: AA(sqrt(2)) / AA(sqrt(8)) # indirect doctest 

0.500000000000000? 

""" 

sk = type(self._descr) 

ok = type(other._descr) 

return type(self)(_binop_algo[sk,ok](self, other, operator.truediv)) 

 

def __invert__(self): 

""" 

TESTS:: 

 

sage: ~AA(sqrt(~2)) 

1.414213562373095? 

""" 

sd = self._descr 

return type(self)(self._descr.invert(self)) 

 

def _add_(self, other): 

""" 

TESTS:: 

 

sage: x = polygen(ZZ) 

sage: rt1, rt2 = (x^2 - x - 1).roots(ring=AA, multiplicities=False) 

sage: rt1 + rt2 # indirect doctest 

1.000000000000000? 

""" 

sk = type(self._descr) 

ok = type(other._descr) 

return type(self)(_binop_algo[sk,ok](self, other, operator.add)) 

 

def _sub_(self, other): 

""" 

TESTS:: 

 

sage: AA(golden_ratio) * 2 - AA(5).sqrt() # indirect doctest 

1.000000000000000? 

""" 

sk = type(self._descr) 

ok = type(other._descr) 

return type(self)(_binop_algo[sk,ok](self, other, operator.sub)) 

 

def _neg_(self): 

""" 

TESTS:: 

 

sage: -QQbar(I) # indirect doctest 

-I 

""" 

return type(self)(self._descr.neg(self)) 

 

def __abs__(self): 

""" 

TESTS:: 

 

sage: abs(AA(sqrt(2) - sqrt(3))) 

0.3178372451957823? 

sage: abs(QQbar(3+4*I)) 

5 

sage: v = QQbar.zeta(3) + 1 

sage: v.exactify() 

sage: v.abs().minpoly() 

x - 1 

""" 

return AlgebraicReal(self._descr.abs(self)) 

 

def __hash__(self): 

""" 

Compute a hash code for this number (equal algebraic numbers will 

have the same hash code, different algebraic numbers are likely 

to have different hash codes). 

 

This may trigger exact computation, but that is very unlikely. 

 

TESTS: 

 

The hash code is stable, even when the representation changes:: 

 

sage: two = QQbar(4).nth_root(4)^2 

sage: two 

2.000000000000000? 

sage: h1 = hash(two) 

sage: two == 2 

True 

sage: two 

2 

sage: h2 = hash(two) 

sage: h1 == h2 

True 

 

sage: h1 = hash(QQbar.zeta(6)) 

sage: h2 = hash(QQbar(1/2 + I*sqrt(3)/2)) 

sage: h1 == h2 

True 

 

Unfortunately, the hash code for algebraic numbers which are close 

enough to each other are the same. (This is inevitable, if 

equal algebraic reals give the same hash code and hashing does 

not always trigger exact computation.):: 

 

sage: h1 = hash(QQbar(0)) 

sage: h2 = hash(QQbar(1/2^100)) 

sage: hash(h1) == hash(h2) 

True 

 

""" 

 

# The only way I can think of to hash algebraic numbers without 

# always triggering exact computation is to use interval_exact(). 

# However, interval_exact() always triggers exact computation 

# if the number is exactly representable in floating point, which 

# is presumably not too unlikely (algebraic reals like 0, 1/2, 

# 1, or 2 are presumably not uncommon). 

 

# So I modify the algebraic real by adding 1/123456789 to it before 

# calling interval_exact(). Then, exact computation will be triggered 

# by algebraic reals which are sufficiently close to 

# (some floating point number minus 1/123456789). Hopefully, 

# -1/123456789 comes up in algebraic real computations far less 

# often than 0 does. Algebraic numbers have a similar offset added, 

# with an additional complex component of 1/987654321*I. 

 

# All of this effort to avoid exact computation is probably wasted, 

# anyway... in almost all uses of hash codes, if the hash codes 

# match, the next step is to compare for equality; and comparing 

# for equality often requires exact computation. (If a==b, 

# then checking a==b requires exact computation unless (a is b).) 

 

if self.parent() is AA: 

return hash((self + AA_hash_offset).interval_exact(RIF)) 

else: 

return hash((self + QQbar_hash_offset).interval_exact(CIF)) 

 

def __bool__(self): 

""" 

Check whether ``self`` is nonzero. 

 

This is fast if interval arithmetic proves it and in many other cases. 

Though, it might be slow in very particular cases where the number is 

actually zero or very close to zero. 

 

EXAMPLES:: 

 

sage: bool(QQbar.zeta(2) + 1) 

False 

sage: bool(QQbar.zeta(7) / (2^500)) 

True 

 

sage: bool(QQbar(I).imag()) 

True 

sage: bool(QQbar(I).real()) 

False 

 

The following is very fast, even though the number is really small:: 

 

sage: a1 = QQbar(2).sqrt() - 16616132878186749607/11749380235262596085 

sage: a2 = QQbar(2).sqrt() - 16616132878186749607/11749380235262596085 

sage: bool(a1 + a2) 

True 

sage: bool(a1 - a2) 

False 

 

sage: a = QQbar(2).sqrt() - 16616132878186749607/11749380235262596085 

sage: b = QQbar(2).sqrt() - 6882627592338442563/4866752642924153522 

sage: c = QQbar(3).sqrt() - 142437039878091970439/82236063316189858921 

sage: d = (59/2)**(1000/7) 

sage: e = (a + b + c) * (a + b - c) * (a - b) * (a - b - c) / d 

sage: bool(e) 

True 

sage: bool(e.abs() < 2**-500) 

True 

 

An identity between roots of unity:: 

 

sage: z3 = QQbar.zeta(3) 

sage: z4 = QQbar.zeta(4) 

sage: z5 = QQbar.zeta(5) 

sage: p1 = (z3 + z4 + z5)**2 

sage: p2 = (z3 - z4 - z5)**2 

sage: p3 = (z3 - z4 + z5)**2 

sage: p4 = (z3 + z4 - z5)**2 

sage: bool(p1 - p2 + p3 - p4 - 8 * QQbar.zeta(15)**8) 

False 

 

Test some non-trivial zeros:: 

 

sage: x = polygen(ZZ) 

sage: a = (AA(2).sqrt() + AA(3).sqrt() + AA(5).sqrt())^2 

sage: b = 10 + 2*max((x^4 - 62*x^2 - 240*x - 239).roots(AA, False)) 

sage: bool(a - b) 

False 

 

sage: d = sum(AA(k)**(1/k) for k in [2..100]) 

sage: bool(d * (a - b)) 

False 

sage: bool((a - b) * d) 

False 

sage: bool(d * (a - b) * d) 

False 

sage: bool((a - b) / d) 

False 

 

sage: d = sum(QQbar(-k)**(1/k) for k in [2..100]) 

sage: bool(d * (a - b)) 

False 

sage: bool((a - b) * d) 

False 

sage: bool(d * (a - b) * d) 

False 

sage: bool((a - b) / d) 

False 

""" 

# case 0: trivial tests 

if not self._value.contains_zero(): 

return True 

elif self._value.is_zero(): 

if not isinstance(self._descr, ANRational): 

self._set_descr(ANRational(QQ.zero())) 

return False 

 

# case 1: cheap tests 

sd = self._descr 

if isinstance(sd, ANExtensionElement): 

# The ANExtensionElement returns an ANRational 

# instead, if the number is zero. 

return True 

elif isinstance(sd, ANRational): 

return bool(sd._value) 

elif isinstance(sd, ANUnaryExpr) and sd._op != 'real' and sd._op != 'imag': 

ans = bool(sd._arg) 

if not ans: 

self._set_descr(ANRational(QQ.zero())) 

return ans 

elif isinstance(sd, ANBinaryExpr) and sd._op is operator.mul: 

ans = bool(sd._left) and bool(sd._right) 

if not ans: 

self._set_descr(ANRational(QQ.zero())) 

return ans 

elif isinstance(sd, ANBinaryExpr) and sd._op is operator.truediv: 

ans = bool(sd._left) 

if not ans: 

self._set_descr(ANRational(QQ.zero())) 

return ans 

 

# case 2: try more precision 

if self._value.prec() < 128: 

self._more_precision() 

if not self._value.contains_zero(): 

return True 

 

# case 3: try with minpoly in case of x+y or x-y 

if isinstance(sd, ANBinaryExpr): 

op = sd._op 

left = sd._left 

right = sd._right if op is operator.sub else -sd._right 

 

lp = left.minpoly() 

rp = right.minpoly() 

if lp != rp: 

return True 

 

c = cmp_elements_with_same_minpoly(left, right, left.minpoly()) 

if c is not None: 

if c == 0: 

self._set_descr(ANRational(QQ.zero())) 

return bool(c) 

 

# Sigh... 

self.exactify() 

return bool(self) 

 

__nonzero__ = __bool__ 

 

def is_square(self): 

""" 

Return whether or not this number is square. 

 

OUTPUT: 

 

(boolean) True in all cases for elements of QQbar; True for 

non-negative elements of AA, otherwise False. 

 

EXAMPLES:: 

 

sage: AA(2).is_square() 

True 

sage: AA(-2).is_square() 

False 

sage: QQbar(-2).is_square() 

True 

sage: QQbar(I).is_square() 

True 

""" 

if self.parent() is AA: 

return bool(self >= 0) 

else: 

return True 

 

def is_integer(self): 

""" 

Return True if this number is a integer 

 

EXAMPLES:: 

 

sage: QQbar(2).is_integer() 

True 

sage: QQbar(1/2).is_integer() 

False 

""" 

return self in ZZ 

 

def sqrt(self, all=False, extend=True): 

""" 

Return the square root(s) of this number. 

 

INPUT: 

 

- ``extend`` - bool (default: True); ignored if self is in QQbar, or 

positive in AA. If self is negative in AA, do the following: if True, 

return a square root of self in QQbar, otherwise raise a ValueError. 

 

- ``all`` - bool (default: False); if True, return a list of all square 

roots. If False, return just one square root, or raise an ValueError 

if self is a negative element of AA and extend=False. 

 

OUTPUT: 

 

Either the principal square root of self, or a list of its 

square roots (with the principal one first). 

 

EXAMPLES:: 

 

sage: AA(2).sqrt() 

1.414213562373095? 

 

sage: QQbar(I).sqrt() 

0.7071067811865475? + 0.7071067811865475?*I 

sage: QQbar(I).sqrt(all=True) 

[0.7071067811865475? + 0.7071067811865475?*I, -0.7071067811865475? - 0.7071067811865475?*I] 

 

sage: a = QQbar(0) 

sage: a.sqrt() 

0 

sage: a.sqrt(all=True) 

[0] 

 

sage: a = AA(0) 

sage: a.sqrt() 

0 

sage: a.sqrt(all=True) 

[0] 

 

This second example just shows that the program doesn't care where 0 

is defined, it gives the same answer regardless. After all, how many 

ways can you square-root zero? 

 

:: 

 

sage: AA(-2).sqrt() 

1.414213562373095?*I 

 

sage: AA(-2).sqrt(all=True) 

[1.414213562373095?*I, -1.414213562373095?*I] 

 

sage: AA(-2).sqrt(extend=False) 

Traceback (most recent call last): 

... 

ValueError: -2 is not a square in AA, being negative. Use extend = True for a square root in QQbar. 

 

 

""" 

# deal with 0 first: 

 

if self.is_zero(): 

if all: 

return [self] 

else: 

return self 

 

# raise an error if appropriate: 

 

if self.parent() is AA and self<0 and not extend: 

if not all: 

raise ValueError("%s is not a square in AA, being negative. Use extend = True for a square root in QQbar."%self) 

else: 

return [] 

 

root = self ** ~ZZ(2) 

 

if all: 

return [root, -root] 

else: 

return root 

 

def nth_root(self, n, all=False): 

r""" 

Return the ``n``-th root of this number. 

 

INPUT: 

 

- ``all`` - bool (default: ``False``). If ``True``, return a list of 

all `n`-th roots as complex algebraic numbers. 

 

.. WARNING:: 

 

Note that for odd `n`, all=`False` and negative real numbers, 

``AlgebraicReal`` and ``AlgebraicNumber`` values give different 

answers: ``AlgebraicReal`` values prefer real results, and 

``AlgebraicNumber`` values return the principal root. 

 

EXAMPLES:: 

 

sage: AA(-8).nth_root(3) 

-2 

sage: QQbar(-8).nth_root(3) 

1.000000000000000? + 1.732050807568878?*I 

sage: QQbar.zeta(12).nth_root(15) 

0.9993908270190957? + 0.03489949670250097?*I 

 

You can get all ``n``-th roots of algebraic numbers:: 

 

sage: AA(-8).nth_root(3, all=True) 

[1.000000000000000? + 1.732050807568878?*I, 

-2.000000000000000? + 0.?e-18*I, 

1.000000000000000? - 1.732050807568878?*I] 

 

sage: QQbar(1+I).nth_root(4, all=True) 

[1.069553932363986? + 0.2127475047267431?*I, 

-0.2127475047267431? + 1.069553932363986?*I, 

-1.069553932363986? - 0.2127475047267431?*I, 

0.2127475047267431? - 1.069553932363986?*I] 

 

TESTS:: 

 

sage: AA(-8).nth_root(3, all=True)[1] 

-2.000000000000000? + 0.?e-18*I 

sage: _.parent() 

Algebraic Field 

 

sage: AA(-2).nth_root(5, all=True) == QQbar(-2).nth_root(5, all=True) # long time 

True 

""" 

if not all: 

return self ** ~ZZ(n) 

else: 

root = QQbar(self) ** ~ZZ(n) 

zlist = [root] 

zeta = QQbar.zeta(n) 

for k in range(1, n): 

root *= zeta 

zlist.append(root) 

return zlist 

 

def as_number_field_element(self, minimal=False): 

r""" 

Returns a number field containing this value, a representation of 

this value as an element of that number field, and a homomorphism 

from the number field back to ``AA`` or ``QQbar``. 

 

This may not return the smallest such number field, unless 

``minimal=True`` is specified. 

 

To compute a single number field containing multiple algebraic 

numbers, use the function 

``number_field_elements_from_algebraics`` instead. 

 

EXAMPLES:: 

 

sage: QQbar(sqrt(8)).as_number_field_element() 

(Number Field in a with defining polynomial y^2 - 2, 2*a, Ring morphism: 

From: Number Field in a with defining polynomial y^2 - 2 

To: Algebraic Real Field 

Defn: a |--> 1.414213562373095?) 

sage: x = polygen(ZZ) 

sage: p = x^3 + x^2 + x + 17 

sage: (rt,) = p.roots(ring=AA, multiplicities=False); rt 

-2.804642726932742? 

sage: (nf, elt, hom) = rt.as_number_field_element() 

sage: nf, elt, hom 

(Number Field in a with defining polynomial y^3 - 2*y^2 - 31*y - 50, a^2 - 5*a - 19, Ring morphism: 

From: Number Field in a with defining polynomial y^3 - 2*y^2 - 31*y - 50 

To: Algebraic Real Field 

Defn: a |--> 7.237653139801104?) 

sage: hom(elt) == rt 

True 

 

We see an example where we do not get the minimal number field unless 

we specify ``minimal=True``:: 

 

sage: rt2 = AA(sqrt(2)) 

sage: rt3 = AA(sqrt(3)) 

sage: rt3b = rt2 + rt3 - rt2 

sage: rt3b.as_number_field_element() 

(Number Field in a with defining polynomial y^4 - 4*y^2 + 1, -a^2 + 2, Ring morphism: 

From: Number Field in a with defining polynomial y^4 - 4*y^2 + 1 

To: Algebraic Real Field 

Defn: a |--> 0.5176380902050415?) 

sage: rt3b.as_number_field_element(minimal=True) 

(Number Field in a with defining polynomial y^2 - 3, a, Ring morphism: 

From: Number Field in a with defining polynomial y^2 - 3 

To: Algebraic Real Field 

Defn: a |--> 1.732050807568878?) 

""" 

return number_field_elements_from_algebraics(self, minimal=minimal) 

 

def exactify(self): 

""" 

Compute an exact representation for this number. 

 

EXAMPLES:: 

 

sage: two = QQbar(4).nth_root(4)^2 

sage: two 

2.000000000000000? 

sage: two.exactify() 

sage: two 

2 

""" 

od = self._descr 

if isinstance(od, (ANRational, ANExtensionElement)): return 

self._set_descr(self._descr.exactify()) 

 

def _set_descr(self, new_descr): 

""" 

Set ``self._descr`` to ``new_descr``, and update 

``self._value`` accordingly. 

 

EXAMPLES:: 

 

sage: c = QQbar(-1)**(1/3) - QQbar(3)**(1/2)/2*QQbar.gen() 

sage: c._value 

0.5000000000000000000? + 0.?e-19*I 

sage: c.exactify() # indirect doctest 

sage: c._value 

0.500000000000000000000? 

""" 

self._descr = new_descr 

new_val = self._descr._interval_fast(self.parent().default_interval_prec()) 

if is_RealIntervalFieldElement(new_val) and is_ComplexIntervalFieldElement(self._value): 

self._value = self._value.real().intersection(new_val) 

elif is_RealIntervalFieldElement(self._value) and is_ComplexIntervalFieldElement(new_val): 

self._value = self._value.intersection(new_val.real()) 

else: 

self._value = self._value.intersection(new_val) 

 

def simplify(self): 

""" 

Compute an exact representation for this number, in the 

smallest possible number field. 

 

EXAMPLES:: 

 

sage: rt2 = AA(sqrt(2)) 

sage: rt3 = AA(sqrt(3)) 

sage: rt2b = rt3 + rt2 - rt3 

sage: rt2b.exactify() 

sage: rt2b._exact_value() 

a^3 - 3*a where a^4 - 4*a^2 + 1 = 0 and a in 1.931851652578137? 

sage: rt2b.simplify() 

sage: rt2b._exact_value() 

a where a^2 - 2 = 0 and a in 1.414213562373095? 

""" 

self.exactify() 

od = self._descr 

if od.is_simple(): return 

self._set_descr(od.simplify(self)) 

 

def _exact_field(self): 

""" 

Returns a generator for a number field that includes this number 

(not necessarily the smallest such number field). 

 

EXAMPLES:: 

 

sage: QQbar(2)._exact_field() 

Trivial generator 

sage: (sqrt(QQbar(2)) + sqrt(QQbar(19)))._exact_field() 

Number Field in a with defining polynomial y^4 - 20*y^2 + 81 with a in 2.375100220297941? 

sage: (QQbar(7)^(3/5))._exact_field() 

Number Field in a with defining polynomial y^5 - 2*y^4 - 18*y^3 + 38*y^2 + 82*y - 181 with a in 2.554256611698490? 

""" 

 

sd = self._descr 

if isinstance(sd, (ANRational, ANExtensionElement)): 

return sd.generator() 

self.exactify() 

return self._exact_field() 

 

def _exact_value(self): 

r""" 

Returns an ``ANRational`` or an ``ANExtensionElement`` representing this 

value. 

 

EXAMPLES:: 

 

sage: QQbar(2)._exact_value() 

2 

sage: (sqrt(QQbar(2)) + sqrt(QQbar(19)))._exact_value() 

-1/9*a^3 - a^2 + 11/9*a + 10 where a^4 - 20*a^2 + 81 = 0 and a in 2.375100220297941? 

sage: (QQbar(7)^(3/5))._exact_value() 

2*a^4 + 2*a^3 - 34*a^2 - 17*a + 150 where a^5 - 2*a^4 - 18*a^3 + 38*a^2 + 82*a - 181 = 0 and a in 2.554256611698490? 

""" 

sd = self._descr 

if isinstance(sd, (ANRational, ANExtensionElement)): 

return sd 

self.exactify() 

return self._descr 

 

def _more_precision(self): 

""" 

Recompute the interval bounding this number with higher-precision 

interval arithmetic. 

 

EXAMPLES:: 

 

sage: rt2 = sqrt(QQbar(2)) 

sage: rt2._value 

1.4142135623730950488? 

sage: rt2._more_precision() 

sage: rt2._value 

1.41421356237309504880168872420969807857? 

sage: rt2._more_precision() 

sage: rt2._value 

1.41421356237309504880168872420969807856967187537694807317667973799073247846211? 

""" 

prec = self._value.prec() 

self._value = self._descr._interval_fast(prec*2) 

 

def minpoly(self): 

""" 

Compute the minimal polynomial of this algebraic number. 

The minimal polynomial is the monic polynomial of least degree 

having this number as a root; it is unique. 

 

EXAMPLES:: 

 

sage: QQbar(4).sqrt().minpoly() 

x - 2 

sage: ((QQbar(2).nth_root(4))^2).minpoly() 

x^2 - 2 

sage: v = sqrt(QQbar(2)) + sqrt(QQbar(3)); v 

3.146264369941973? 

sage: p = v.minpoly(); p 

x^4 - 10*x^2 + 1 

sage: p(RR(v.real())) 

1.31006316905768e-14 

""" 

try: 

return self._minimal_polynomial 

except AttributeError: 

self.exactify() 

self._minimal_polynomial = self._descr.minpoly() 

return self._minimal_polynomial 

 

def degree(self): 

""" 

Return the degree of this algebraic number (the degree of its 

minimal polynomial, or equivalently, the degree of the smallest 

algebraic extension of the rationals containing this number). 

 

EXAMPLES:: 

 

sage: QQbar(5/3).degree() 

1 

sage: sqrt(QQbar(2)).degree() 

2 

sage: QQbar(17).nth_root(5).degree() 

5 

sage: sqrt(3+sqrt(QQbar(8))).degree() 

2 

""" 

return self.minpoly().degree() 

 

def interval_fast(self, field): 

r""" 

Given a :class:`RealIntervalField` or 

:class:`ComplexIntervalField`, compute the value of this number 

using interval arithmetic of at least the precision of the field, 

and return the value in that field. (More precision may be used 

in the computation.) The returned interval may be arbitrarily 

imprecise, if this number is the result of a sufficiently long 

computation chain. 

 

EXAMPLES:: 

 

sage: x = AA(2).sqrt() 

sage: x.interval_fast(RIF) 

1.414213562373095? 

sage: x.interval_fast(RealIntervalField(200)) 

1.414213562373095048801688724209698078569671875376948073176680? 

sage: x = QQbar(I).sqrt() 

sage: x.interval_fast(CIF) 

0.7071067811865475? + 0.7071067811865475?*I 

sage: x.interval_fast(RIF) 

Traceback (most recent call last): 

... 

TypeError: unable to convert complex interval 0.7071067811865475244? + 0.7071067811865475244?*I to real interval 

""" 

while self._value.prec() < field.prec(): 

self._more_precision() 

return field(self._value) 

 

def interval_diameter(self, diam): 

""" 

Compute an interval representation of self with ``diameter()`` at 

most ``diam``. The precision of the returned value is unpredictable. 

 

EXAMPLES:: 

 

sage: AA(2).sqrt().interval_diameter(1e-10) 

1.4142135623730950488? 

sage: AA(2).sqrt().interval_diameter(1e-30) 

1.41421356237309504880168872420969807857? 

sage: QQbar(2).sqrt().interval_diameter(1e-10) 

1.4142135623730950488? 

sage: QQbar(2).sqrt().interval_diameter(1e-30) 

1.41421356237309504880168872420969807857? 

""" 

if diam <= 0: 

raise ValueError('diameter must be positive in interval_diameter') 

 

while self._value.diameter() > diam: 

self._more_precision() 

 

return self._value 

 

def interval(self, field): 

r""" 

Given an interval field (real or complex, as appropriate) of 

precision `p`, compute an interval representation of self with 

``diameter()`` at most `2^{-p}`; then round that representation into 

the given field. Here ``diameter()`` is relative diameter for 

intervals not containing 0, and absolute diameter for 

intervals that do contain 0; thus, if the returned interval 

does not contain 0, it has at least `p-1` good bits. 

 

EXAMPLES:: 

 

sage: RIF64 = RealIntervalField(64) 

sage: x = AA(2).sqrt() 

sage: y = x*x 

sage: y = 1000 * y - 999 * y 

sage: y.interval_fast(RIF64) 

2.000000000000000? 

sage: y.interval(RIF64) 

2.000000000000000000? 

sage: CIF64 = ComplexIntervalField(64) 

sage: x = QQbar.zeta(11) 

sage: x.interval_fast(CIF64) 

0.8412535328311811689? + 0.5406408174555975821?*I 

sage: x.interval(CIF64) 

0.8412535328311811689? + 0.5406408174555975822?*I 

 

The following implicitly use this method:: 

 

sage: RIF(AA(5).sqrt()) 

2.236067977499790? 

sage: AA(-5).sqrt().interval(RIF) 

Traceback (most recent call last): 

... 

TypeError: unable to convert 2.236067977499790?*I to real interval 

 

TESTS: 

 

Check that :trac:`20209` is fixed:: 

 

sage: RIF(QQbar(2).sqrt()) 

1.414213562373095? 

sage: RIF(QQbar.gen() + QQbar(2).sqrt() - QQbar.gen()) 

1.414213562373095? 

sage: RIF((QQbar.gen() + QQbar(2).sqrt() - QQbar.gen()).sqrt()) 

1.189207115002722? 

 

sage: RealIntervalField(129)(QQbar(3).sqrt()) 

1.73205080756887729352744634150587236695? 

sage: RIF(QQbar.gen()) 

Traceback (most recent call last): 

... 

TypeError: unable to convert I to real interval 

""" 

target = RR(1.0) >> field.prec() 

val = self.interval_diameter(target) 

if isinstance(field, RealIntervalField_class) and is_ComplexIntervalFieldElement(val): 

if val.imag().is_zero(): 

return field(val.real()) 

elif self.imag().is_zero(): 

return field(self.real()) 

else: 

raise TypeError("unable to convert {} to real interval".format(self)) 

else: 

return field(val) 

 

_complex_mpfi_ = _real_mpfi_ = interval 

 

def radical_expression(self): 

r""" 

Attempt to obtain a symbolic expression using radicals. If no 

exact symbolic expression can be found, the algebraic number 

will be returned without modification. 

 

EXAMPLES:: 

 

sage: AA(1/sqrt(5)).radical_expression() 

sqrt(1/5) 

sage: AA(sqrt(5 + sqrt(5))).radical_expression() 

sqrt(sqrt(5) + 5) 

sage: QQbar.zeta(5).radical_expression() 

1/4*sqrt(5) + 1/2*sqrt(-1/2*sqrt(5) - 5/2) - 1/4 

sage: a = QQ[x](x^7 - x - 1).roots(AA, False)[0] 

sage: a.radical_expression() 

1.112775684278706? 

sage: a.radical_expression().parent() == SR 

False 

sage: a = sorted(QQ[x](x^7-x-1).roots(QQbar, False), key=imag)[0] 

sage: a.radical_expression() 

-0.3636235193291805? - 0.9525611952610331?*I 

sage: QQbar.zeta(5).imag().radical_expression() 

1/2*sqrt(1/2*sqrt(5) + 5/2) 

sage: AA(5/3).radical_expression() 

5/3 

sage: AA(5/3).radical_expression().parent() == SR 

True 

sage: QQbar(0).radical_expression() 

0 

 

TESTS: 

 

In this example we find the correct answer despite the fact that 

multiple roots overlap with the current value. As a consequence, 

the precision of the evaluation will have to be increased. 

 

:: 

 

sage: a = AA(sqrt(2) + 10^25) 

sage: p = a.minpoly() 

sage: v = a._value 

sage: f = ComplexIntervalField(v.prec()) 

sage: [f(b.rhs()).overlaps(f(v)) for b in SR(p).solve(x)] 

[True, True] 

sage: a.radical_expression() 

sqrt(2) + 10000000000000000000000000 

""" 

from sage.symbolic.ring import SR # Lazy to avoid cyclic dependency 

 

# Adapted from NumberFieldElement._symbolic_() 

poly = self.minpoly() 

var = SR(poly.variable_name()) 

if is_ComplexIntervalFieldElement(self._value): 

interval_field = self._value.parent() 

else: 

interval_field = ComplexIntervalField(self._value.prec()) 

roots = poly.roots(SR, multiplicities=False) 

if len(roots) != poly.degree(): 

return self 

while True: 

candidates = [] 

for root in roots: 

if interval_field(root).overlaps(interval_field(self._value)): 

candidates.append(root) 

if len(candidates) == 1: 

return candidates[0] 

roots = candidates 

interval_field = interval_field.to_prec(interval_field.prec()*2) 

 

 

class AlgebraicNumber(AlgebraicNumber_base): 

r""" 

The class for algebraic numbers (complex numbers which are the roots 

of a polynomial with integer coefficients). Much of its functionality 

is inherited from ``AlgebraicNumber_base``. 

 

.. automethod:: _richcmp_ 

""" 

def __init__(self, x): 

r""" 

Initialize this AlgebraicNumber object. 

 

EXAMPLES:: 

 

sage: t = QQbar.zeta(5) 

sage: type(t) 

<class 'sage.rings.qqbar.AlgebraicNumber'> 

""" 

AlgebraicNumber_base.__init__(self, QQbar, x) 

 

def __reduce__(self): 

""" 

Add customized pickling support. 

 

EXAMPLES:: 

 

sage: t = QQbar.zeta(5) 

sage: loads(dumps(t)) == t 

True 

""" 

return (AlgebraicNumber, (self._descr, )) 

 

def _richcmp_(self, other, op): 

r""" 

Compare two algebraic numbers, lexicographically. (That is, 

first compare the real components; if the real components are 

equal, compare the imaginary components.) 

 

EXAMPLES:: 

 

sage: x = QQbar.zeta(3); x 

-0.500000000000000? + 0.866025403784439?*I 

sage: QQbar(-1) < x 

True 

sage: QQbar(-1/2) < x 

True 

sage: QQbar(0) > x 

True 

 

One problem with this lexicographic ordering is the fact that if 

two algebraic numbers have the same real component, that real 

component has to be compared for exact equality, which can be 

a costly operation. For the special case where both numbers 

have the same minimal polynomial, that cost can be avoided, 

though (see :trac:`16964`):: 

 

sage: x = polygen(ZZ) 

sage: p = 69721504*x^8 + 251777664*x^6 + 329532012*x^4 + 184429548*x^2 + 37344321 

sage: sorted(p.roots(QQbar,False)) 

[-0.0221204634374361? - 1.090991904211621?*I, 

-0.0221204634374361? + 1.090991904211621?*I, 

-0.8088604911480535?*I, 

0.?e-79 - 0.7598602580415435?*I, 

0.?e-79 + 0.7598602580415435?*I, 

0.8088604911480535?*I, 

0.0221204634374361? - 1.090991904211621?*I, 

0.0221204634374361? + 1.090991904211621?*I] 

 

It also works for comparison of conjugate roots even in a degenerate 

situation where many roots have the same real part. In the following 

example, the polynomial ``p2`` is irreducible and all its roots have 

real part equal to `1`:: 

 

sage: p1 = x^8 + 74*x^7 + 2300*x^6 + 38928*x^5 + \ 

....: 388193*x^4 + 2295312*x^3 + 7613898*x^2 + \ 

....: 12066806*x + 5477001 

sage: p2 = p1((x-1)^2) 

sage: sum(1 for r in p2.roots(CC,False) if abs(r.real() - 1) < 0.0001) 

16 

sage: r1 = QQbar.polynomial_root(p2, CIF(1, (-4.1,-4.0))) 

sage: r2 = QQbar.polynomial_root(p2, CIF(1, (4.0, 4.1))) 

sage: all([r1<r2, r1==r1, r2==r2, r2>r1]) 

True 

 

Though, comparing roots which are not equal or conjugate is much 

slower because the algorithm needs to check the equality of the real 

parts:: 

 

sage: sorted(p2.roots(QQbar,False)) # long time - 3 secs 

[1.000000000000000? - 4.016778562562223?*I, 

1.000000000000000? - 3.850538755978243?*I, 

1.000000000000000? - 3.390564396412898?*I, 

... 

1.000000000000000? + 3.390564396412898?*I, 

1.000000000000000? + 3.850538755978243?*I, 

1.000000000000000? + 4.016778562562223?*I] 

 

TESTS:: 

 

sage: QQbar.zeta(6) == QQbar(1/2 + I*sqrt(3)/2) 

True 

sage: QQbar(I) == QQbar(I * (2^100+1)/(2^100)) 

False 

sage: QQbar(2) == 2 

True 

sage: QQbar(2) == GF(7)(2) 

False 

sage: GF(7)(2) in QQbar 

False 

 

sage: QQbar.zeta(6) != QQbar(1/2 + I*sqrt(3)/2) 

False 

sage: QQbar(I) != QQbar(I * (2^100+1)/(2^100)) 

True 

sage: QQbar(2) != 2 

False 

sage: QQbar(2) != GF(7)(2) 

True 

 

sage: QQbar.zeta(3).real() == -1/2 

True 

""" 

# note: we can assume that self is not other here 

sd = self._descr 

od = other._descr 

 

if isinstance(sd, ANRational) and isinstance(od, ANRational): 

return richcmp(sd._value, od._value, op) 

 

if op == op_EQ or op == op_NE: 

# some cheap and quite common tests where we can decide 

# equality or difference 

if not (self._value.real().overlaps(other._value.real()) and 

self._value.imag().overlaps(other._value.imag())): 

return op == op_NE 

if isinstance(sd, ANRational) and not sd._value: 

return bool(other) == (op == op_NE) 

elif isinstance(od, ANRational) and not od._value: 

return bool(self) == (op == op_NE) 

elif (isinstance(sd, ANExtensionElement) and 

isinstance(od, ANExtensionElement) and 

sd._generator is od._generator): 

return sd._value == od._value if op == op_EQ else sd._value != od._value 

 

# case 0: real parts are clearly distinct 

ri1 = self._value.real() 

ri2 = other._value.real() 

if not ri1.overlaps(ri2): 

return richcmp_not_equal(ri1, ri2, op) 

 

# case 1: rationals 

sd = self._descr 

od = other._descr 

if isinstance(sd, ANRational) and isinstance(od, ANRational): 

return richcmp(sd._value, od._value, op) 

 

# case 2: possibly equal or conjugate values 

# (this case happen a lot when sorting the roots of a real polynomial) 

ci1 = self._value.imag().abs() 

ci2 = other._value.imag().abs() 

if ci1.overlaps(ci2) and self.minpoly() == other.minpoly(): 

c = cmp_elements_with_same_minpoly(self, other, self.minpoly()) 

if c is not None: 

return rich_to_bool(op, c) 

 

# case 3: try hard to compare real parts and imaginary parts 

srp = self.real() 

orp = other.real() 

if srp != orp: 

return richcmp_not_equal(srp, orp, op) 

return richcmp(self.imag(), other.imag(), op) 

 

def _mpfr_(self, field): 

r""" 

Given a ``RealField``, compute a good approximation to self in 

that field. Works only if the imaginary component of self is 

exactly zero; otherwise it raises a ``ValueError``. 

 

EXAMPLES:: 

 

sage: QQbar(sqrt(2))._mpfr_(RR) 

1.41421356237309 

sage: QQbar(-22/7)._mpfr_(RR) 

-3.14285714285714 

sage: QQbar.zeta(3)._mpfr_(RR) 

Traceback (most recent call last): 

... 

ValueError: Cannot coerce algebraic number with non-zero imaginary part to algebraic real 

""" 

return AA(self)._mpfr_(field) 

 

def __float__(self): 

r""" 

Compute a good float approximation to self. Works only if the 

imaginary component of self is exactly zero; otherwise it 

raises a ``ValueError``. 

 

EXAMPLES:: 

 

sage: QQbar(sqrt(2)).__float__() 

1.414213562373095 

sage: float(QQbar(-22/7)) 

-3.1428571428571432 

sage: float(QQbar.zeta(3)) 

Traceback (most recent call last): 

... 

ValueError: Cannot coerce algebraic number with non-zero imaginary part to algebraic real 

""" 

return AA(self).__float__() 

 

def __complex__(self): 

r""" 

Compute a good complex approximation to self. 

 

EXAMPLES:: 

 

sage: QQbar(sqrt(2)).__complex__() 

(1.414213562373095+0j) 

sage: complex(QQbar.zeta(3)) 

(-0.5+0.8660254037844386j) 

""" 

return CC(self).__complex__() 

 

def _complex_double_(self, cdf): 

r""" 

Compute a good approximation to self in CDF. 

 

EXAMPLES:: 

 

sage: QQbar(sqrt(-5))._complex_double_(CDF) 

2.23606797749979*I 

sage: CDF(QQbar.zeta(12)) 

0.8660254037844386 + 0.5*I 

""" 

return cdf(CC(self)) 

 

def _interval_fast(self, prec): 

r""" 

Shortcut for :meth:`AlgebraicNumber_base.interval_fast` which uses the complex interval field. 

 

EXAMPLES:: 

 

sage: QQbar(sqrt(-5))._interval_fast(100) 

2.236067977499789696409173...?*I 

""" 

return self.interval_fast(ComplexIntervalField(prec)) 

 

def _integer_(self, ZZ=None): 

""" 

Return self as an Integer. 

 

EXAMPLES:: 

 

sage: QQbar(0)._integer_() 

0 

sage: QQbar(0)._integer_().parent() 

Integer Ring 

sage: QQbar.zeta(6)._integer_() 

Traceback (most recent call last): 

... 

ValueError: Cannot coerce algebraic number with non-zero imaginary part to algebraic real 

sage: QQbar(sqrt(17))._integer_() 

Traceback (most recent call last): 

... 

ValueError: Cannot coerce non-integral Algebraic Real 4.123105625617660? to Integer 

sage: QQbar(sqrt(16))._integer_() 

4 

sage: v = QQbar(1 + I*sqrt(3))^5 + QQbar(16*sqrt(3)*I); v 

16.00000000000000? + 0.?e-17*I 

sage: v._integer_() 

16 

""" 

return AA(self)._integer_(ZZ) 

 

def _rational_(self): 

""" 

Return self as a Rational. 

 

EXAMPLES:: 

 

sage: QQbar(-22/7)._rational_() 

-22/7 

sage: QQbar(3)._rational_().parent() 

Rational Field 

sage: (QQbar.zeta(7)^3)._rational_() 

Traceback (most recent call last): 

... 

ValueError: Cannot coerce algebraic number with non-zero imaginary part to algebraic real 

sage: QQbar(sqrt(2))._rational_() 

Traceback (most recent call last): 

... 

ValueError: Cannot coerce irrational Algebraic Real 1.414213562373095? to Rational 

sage: v1 = QQbar(1/3 + I*sqrt(5))^7 

sage: v2 = QQbar((100336/729*golden_ratio - 50168/729)*I) 

sage: v = v1 + v2; v 

-259.6909007773206? + 0.?e-15*I 

sage: v._rational_() 

-567944/2187 

""" 

return AA(self)._rational_() 

 

def real(self): 

r""" 

Return the real part of self. 

 

EXAMPLES:: 

 

sage: QQbar.zeta(5).real() 

0.3090169943749474? 

""" 

return AlgebraicReal(self._descr.real(self)) 

 

def imag(self): 

r""" 

Return the imaginary part of self. 

 

EXAMPLES:: 

 

sage: QQbar.zeta(7).imag() 

0.7818314824680299? 

""" 

return AlgebraicReal(self._descr.imag(self)) 

 

def conjugate(self): 

""" 

Returns the complex conjugate of self. 

 

EXAMPLES:: 

 

sage: QQbar(3 + 4*I).conjugate() 

3 - 4*I 

sage: QQbar.zeta(7).conjugate() 

0.6234898018587335? - 0.7818314824680299?*I 

sage: QQbar.zeta(7) + QQbar.zeta(7).conjugate() 

1.246979603717467? + 0.?e-18*I 

""" 

return AlgebraicNumber(self._descr.conjugate(self)) 

 

def norm(self): 

r""" 

Returns ``self * self.conjugate()``. This is the algebraic 

definition of norm, if we view ``QQbar`` as ``AA[I]``. 

 

EXAMPLES:: 

 

sage: QQbar(3 + 4*I).norm() 

25 

sage: type(QQbar(I).norm()) 

<class 'sage.rings.qqbar.AlgebraicReal'> 

sage: QQbar.zeta(1007).norm() 

1.000000000000000? 

""" 

return AlgebraicReal(self._descr.norm(self)) 

 

def interval_exact(self, field): 

r""" 

Given a ``ComplexIntervalField``, compute the best possible 

approximation of this number in that field. Note that if 

either the real or imaginary parts of this number are 

sufficiently close to some floating-point number (and, in 

particular, if either is exactly representable in floating-point), 

then this will trigger exact computation, which may be very slow. 

 

EXAMPLES:: 

 

sage: a = QQbar(I).sqrt(); a 

0.7071067811865475? + 0.7071067811865475?*I 

sage: a.interval_exact(CIF) 

0.7071067811865475? + 0.7071067811865475?*I 

sage: b = QQbar((1+I)*sqrt(2)/2) 

sage: (a - b).interval(CIF) 

0.?e-19 + 0.?e-18*I 

sage: (a - b).interval_exact(CIF) 

0 

""" 

if not is_ComplexIntervalField(field): 

raise ValueError("AlgebraicNumber interval_exact requires a ComplexIntervalField") 

rfld = field._real_field() 

re = self.real().interval_exact(rfld) 

im = self.imag().interval_exact(rfld) 

return field(re, im) 

 

def _complex_mpfr_field_(self, field): 

r""" 

Compute an approximation to self in the given field, which must 

be a complex field. 

 

EXAMPLES:: 

 

sage: a = QQbar(1 + I).sqrt() 

sage: t = a._complex_mpfr_field_(ComplexField(100)); t 

1.0986841134678099660398011952 + 0.45508986056222734130435775782*I 

sage: parent(t) 

Complex Field with 100 bits of precision 

""" 

return self.complex_number(field) 

 

def complex_number(self, field): 

r""" 

Given the complex field ``field`` compute an accurate approximation of 

this element in that field. 

 

The approximation will be off by at most two ulp's in each component, 

except for components which are very close to zero, which will have an 

absolute error at most `2^{-prec+1}` where `prec` is the precision of 

the field. 

 

EXAMPLES:: 

 

sage: a = QQbar.zeta(5) 

sage: a.complex_number(CC) 

0.309016994374947 + 0.951056516295154*I 

 

sage: b = QQbar(2).sqrt() + QQbar(3).sqrt() * QQbar.gen() 

sage: b.complex_number(ComplexField(128)) 

1.4142135623730950488016887242096980786 + 1.7320508075688772935274463415058723669*I 

""" 

v = self.interval(ComplexIntervalField(field.prec())) 

return field(v) 

 

def complex_exact(self, field): 

r""" 

Given a ``ComplexField``, return the best possible approximation of 

this number in that field. Note that if either component is 

sufficiently close to the halfway point between two floating-point 

numbers in the corresponding ``RealField``, then this will trigger 

exact computation, which may be very slow. 

 

EXAMPLES:: 

 

sage: a = QQbar.zeta(9) + QQbar(I) + QQbar.zeta(9).conjugate(); a 

1.532088886237957? + 1.000000000000000?*I 

sage: a.complex_exact(CIF) 

1.532088886237957? + 1*I 

""" 

rfld = field._real_field() 

re = self.real().real_exact(rfld) 

im = self.imag().real_exact(rfld) 

return field(re, im) 

 

def multiplicative_order(self): 

r""" 

Compute the multiplicative order of this algebraic real 

number. That is, find the smallest positive integer `n` such 

that `x^n = 1`. If there is no such `n`, returns ``+Infinity``. 

 

We first check that ``abs(x)`` is very close to 1. If so, we compute 

`x` exactly and examine its argument. 

 

EXAMPLES:: 

 

sage: QQbar(-sqrt(3)/2 - I/2).multiplicative_order() 

12 

sage: QQbar(1).multiplicative_order() 

1 

sage: QQbar(-I).multiplicative_order() 

4 

sage: QQbar(707/1000 + 707/1000*I).multiplicative_order() 

+Infinity 

sage: QQbar(3/5 + 4/5*I).multiplicative_order() 

+Infinity 

""" 

if not (1 in CIF(self).norm()): 

return infinity.infinity 

if self.norm() != 1: 

return infinity.infinity 

d = self.minpoly().is_cyclotomic(True) 

return d if d else infinity.infinity 

 

def rational_argument(self): 

r""" 

Returns the argument of self, divided by `2\pi`, as long as this 

result is rational. Otherwise returns None. Always triggers 

exact computation. 

 

EXAMPLES:: 

 

sage: QQbar((1+I)*(sqrt(2)+sqrt(5))).rational_argument() 

1/8 

sage: QQbar(-1 + I*sqrt(3)).rational_argument() 

1/3 

sage: QQbar(-1 - I*sqrt(3)).rational_argument() 

-1/3 

sage: QQbar(3+4*I).rational_argument() is None 

True 

sage: (QQbar(2)**(1/5) * QQbar.zeta(7)**2).rational_argument() 

2/7 

sage: (QQbar.zeta(73)**5).rational_argument() 

5/73 

sage: (QQbar.zeta(3)^65536).rational_argument() 

1/3 

""" 

# This always triggers exact computation. An alternate method 

# could almost always avoid exact computation when the result 

# is None: if we can compute an upper bound on the degree of 

# this algebraic number without exact computation, we can use 

# the method of ANExtensionElement.rational_argument(). 

 

# Even a very loose upper bound would suffice; for instance, 

# an upper bound of 2^100, when the true degree was 8, would 

# still be efficient. 

 

self.exactify() 

return self._descr.rational_argument(self) 

 

def _pow_(self, other): 

""" 

Powering for ``QQbar(1)``. 

 

EXAMPLES:: 

 

sage: QQbar(1) ^ QQbar(sqrt(2)) 

1 

sage: 1 ^ QQbar(sqrt(2)) 

1 

sage: QQbar(2) ^ QQbar(2) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for ^: 'Algebraic Field' and 'Algebraic Field' 

sage: AA(1) ^ AA(1) 

Traceback (most recent call last): 

... 

TypeError: unsupported operand parent(s) for ^: 'Algebraic Real Field' and 'Algebraic Real Field' 

""" 

# For some crazy unspecified reason, we must allow this if the 

# base is QQbar(1). See Trac #22120 and #24490. 

if self == 1: 

return self 

raise TypeError("unsupported operand parent(s) for ^: '{0}' and '{0}'".format(self.parent())) 

 

 

class AlgebraicReal(AlgebraicNumber_base): 

r""" 

A real algebraic number. 

 

.. automethod:: _richcmp_ 

""" 

def __init__(self, x): 

""" 

Create an algebraic real from x, possibly taking the real part of x. 

 

TESTS: 

 

Both of the following examples, from :trac:`11728`, trigger 

taking the real part below. This is necessary because 

sometimes a very small (e.g., 1e-17) complex part appears in a 

complex interval used to create an AlgebraicReal.:: 

 

sage: a = QQbar((-1)^(1/4)); b = AA(a^3-a); t = b.as_number_field_element() 

sage: b*1 

-1.414213562373095? 

""" 

AlgebraicNumber_base.__init__(self, AA, x) 

self._ensure_real() 

 

def _ensure_real(self): 

""" 

This is used internally by some methods to check if 

self._value is a complex interval, and if so, take the real 

part. 

 

EXAMPLES:: 

 

sage: a = QQbar((-1)^(1/4)); b = AA(a^3-a); b._value 

-1.4142135623730950488? 

sage: b._value = a._value; b._value 

0.7071067811865475244? + 0.7071067811865475244?*I 

sage: b._ensure_real() 

sage: b._value 

0.7071067811865475244? 

sage: type(b._value) 

<type 'sage.rings.real_mpfi.RealIntervalFieldElement'> 

""" 

if is_ComplexIntervalFieldElement(self._value): 

self._value = self._value.real() 

 

def _more_precision(self): 

""" 

Recompute the interval bounding this number with higher-precision 

interval arithmetic. 

 

EXAMPLES:: 

 

sage: a = QQbar(sqrt(2)) 

sage: a._more_precision() 

 

TESTS: 

 

We have to ensure after doing this that self._value is still 

real which isn't the case without calling _ensure_real (see 

:trac:`11728`):: 

 

sage: P = AA['x'](1+x^4); a1,a2 = P.factor()[0][0],P.factor()[1][0]; a1*a2 

x^4 + 1.000000000000000? 

sage: a1,a2 

(x^2 - 1.414213562373095?*x + 1, x^2 + 1.414213562373095?*x + 1) 

sage: a1*a2 

x^4 + 1 

""" 

AlgebraicNumber_base._more_precision(self) 

self._ensure_real() 

 

def __reduce__(self): 

""" 

Add customized pickling support. 

 

EXAMPLES:: 

 

sage: t = AA(sqrt(2)) 

sage: loads(dumps(t)) == t 

True 

""" 

return (AlgebraicReal, (self._descr, )) 

 

def _richcmp_(self, other, op): 

""" 

Compare two algebraic reals. 

 

EXAMPLES:: 

 

sage: AA(2).sqrt() < AA(3).sqrt() 

True 

sage: ((5+AA(5).sqrt())/2).sqrt() == 2*QQbar.zeta(5).imag() 

True 

sage: AA(3).sqrt() + AA(2).sqrt() < 3 

False 

 

TESTS:: 

 

sage: AA(golden_ratio) < AA(sqrt(5)) 

True 

sage: AA(golden_ratio) == AA((sqrt(5)+1)/2) 

True 

sage: AA(7) >= AA(50/7) 

False 

""" 

# note: we can assume that self is not other here 

sd = self._descr 

od = other._descr 

 

if type(sd) is ANRational and type(od) is ANRational: 

return richcmp(sd._value, od._value, op) 

 

if op == op_EQ or op == op_NE: 

# some cheap and quite common tests where we can decide equality or difference 

if not self._value.real().overlaps(other._value.real()): 

return op == op_NE 

if type(sd) is ANRational and not sd._value: 

return bool(other) == (op == op_NE) 

elif type(od) is ANRational and not od._value: 

return bool(self) == (op == op_NE) 

elif (type(sd) is ANExtensionElement and 

type(od) is ANExtensionElement and 

sd._generator is od._generator): 

return sd._value == od._value if op == op_EQ else sd._value != od._value 

elif self.minpoly() != other.minpoly(): 

return op == op_NE 

 

# case 0: real parts are clearly distinct 

if not self._value.overlaps(other._value): 

return richcmp(self._value, other._value, op) 

 

# case 1: rationals 

sd = self._descr 

od = other._descr 

if type(sd) is ANRational and type(od) is ANRational: 

return richcmp(sd._value, od._value, op) 

 

if self._value.prec() < 128: 

self._more_precision() 

if other._value.prec() < 128: 

other._more_precision() 

if not self._value.overlaps(other._value): 

return richcmp(self._value, other._value, op) 

 

return rich_to_bool(op, (self-other).sign()) 

 

def _integer_(self, Z=None): 

""" 

Return self as an Integer. 

 

EXAMPLES:: 

 

sage: AA(42)._integer_() 

42 

sage: AA(42)._integer_().parent() 

Integer Ring 

sage: AA(golden_ratio)._integer_() 

Traceback (most recent call last): 

... 

ValueError: Cannot coerce non-integral Algebraic Real 1.618033988749895? to Integer 

sage: (AA(golden_ratio)^10 + AA(1-golden_ratio)^10)._integer_() 

123 

sage: AA(-22/7)._integer_() 

Traceback (most recent call last): 

... 

ValueError: Cannot coerce non-integral Algebraic Real -22/7 to Integer 

""" 

if self._value.lower().ceiling() > self._value.upper().floor(): 

# The value is known to be non-integral. 

raise ValueError("Cannot coerce non-integral Algebraic Real %s to Integer" % self) 

 

self.exactify() 

if not isinstance(self._descr, ANRational): 

raise ValueError("Cannot coerce irrational Algebraic Real %s to Integer" % self) 

 

return ZZ(self._descr._value) 

 

def _floor_ceil(self, method): 

r""" 

Helper method used by :meth:`floor()`, :meth:`ceil()`, 

:meth:`round()`, and :meth:`trunc()`. 

 

TESTS:: 

 

sage: x = polygen(QQ) 

sage: a = AA.polynomial_root(x^5 - (1-2^(-80)), RIF((0,2))) 

sage: b = AA.polynomial_root(x^5 - (1+2^(-80)), RIF((0,2))) 

sage: two = (a+b)^5 - 5*(a^4*b+a*b^4) - 10*(a^3*b^2+a^2*b^3) 

sage: one_half = 1/two 

sage: [[z.floor(), z.ceil(), z.round(), z.trunc()] # indirect doctest 

....: for z in [a, -a, b, -b, 6*(a+two), 

....: AA(0), AA(1), AA(-1), AA(1/2), AA(-1/2)]] 

[[0, 1, 1, 0], [-1, 0, -1, 0], [1, 2, 1, 1], [-2, -1, -1, -1], 

[17, 18, 18, 17], [0, 0, 0, 0], [1, 1, 1, 1], [-1, -1, -1, -1], 

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

sage: [[z.floor(), z.ceil(), z.trunc()] for z in [two, a*b]] # long time 

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

sage: [one_half.round(), (-one_half).round()] # long time 

[1, -1] 

""" 

for i in itertools.count(): 

candidate = method(self._value.lower()) 

if candidate == method(self._value.upper()): 

return candidate 

self._more_precision() 

# field elements are irrational by construction 

if i == 2 and not isinstance(self._descr, ANExtensionElement): 

try: 

return method(self._rational_()) 

except (ValueError, TypeError): 

pass 

 

def floor(self): 

r""" 

Return the largest integer not greater than ``self``. 

 

EXAMPLES:: 

 

sage: AA(sqrt(2)).floor() 

1 

sage: AA(-sqrt(2)).floor() 

-2 

sage: AA(42).floor() 

42 

 

TESTS: 

 

Check that :trac:`15501` is fixed:: 

 

sage: a = QQbar((-1)^(1/4)).real() 

sage: (floor(a-a) + a).parent() 

Algebraic Real Field 

""" 

return self._floor_ceil(lambda x: x.floor()) 

 

def ceil(self): 

r""" 

Return the smallest integer not smaller than ``self``. 

 

EXAMPLES:: 

 

sage: AA(sqrt(2)).ceil() 

2 

sage: AA(-sqrt(2)).ceil() 

-1 

sage: AA(42).ceil() 

42 

""" 

return self._floor_ceil(lambda x: x.ceil()) 

 

def round(self): 

r""" 

Round ``self`` to the nearest integer. 

 

EXAMPLES:: 

 

sage: AA(sqrt(2)).round() 

1 

sage: AA(1/2).round() 

1 

sage: AA(-1/2).round() 

-1 

""" 

return self._floor_ceil(lambda x: x.round()) 

 

def trunc(self): 

r""" 

Round ``self`` to the nearest integer toward zero. 

 

EXAMPLES:: 

 

sage: AA(sqrt(2)).trunc() 

1 

sage: AA(-sqrt(2)).trunc() 

-1 

sage: AA(1).trunc() 

1 

sage: AA(-1).trunc() 

-1 

""" 

return self._floor_ceil(lambda x: x.trunc()) 

 

def _rational_(self): 

""" 

Return self as a Rational. 

 

EXAMPLES:: 

 

sage: AA(42)._rational_().parent() 

Rational Field 

sage: AA(-22/7)._rational_() 

-22/7 

sage: AA(sqrt(7))._rational_() 

Traceback (most recent call last): 

... 

ValueError: Cannot coerce irrational Algebraic Real 2.645751311064591? to Rational 

sage: v = AA(1/2 + sqrt(2))^3 - AA(11/4*sqrt(2)); v 

3.125000000000000? 

sage: v._rational_() 

25/8 

""" 

self.exactify() 

if not isinstance(self._descr, ANRational): 

raise ValueError("Cannot coerce irrational Algebraic Real %s to Rational" % self) 

 

return QQ(self._descr._value) 

 

def real(self): 

""" 

Returns the real part of this algebraic real (so it always returns 

self). 

 

EXAMPLES:: 

 

sage: a = AA(sqrt(2) + sqrt(3)) 

sage: a.real() 

3.146264369941973? 

sage: a.real() is a 

True 

""" 

return self 

 

def imag(self): 

""" 

Returns the imaginary part of this algebraic real (so it always 

returns 0). 

 

EXAMPLES:: 

 

sage: a = AA(sqrt(2) + sqrt(3)) 

sage: a.imag() 

0 

sage: parent(a.imag()) 

Algebraic Real Field 

""" 

return AA_0 

 

def conjugate(self): 

""" 

Returns the complex conjugate of self, i.e. returns itself. 

 

EXAMPLES:: 

 

sage: a = AA(sqrt(2) + sqrt(3)) 

sage: a.conjugate() 

3.146264369941973? 

sage: a.conjugate() is a 

True 

""" 

return self 

 

def sign(self): 

""" 

Compute the sign of this algebraic number (return -1 if negative, 

0 if zero, or 1 if positive). 

 

Computes an interval enclosing this number using 128-bit interval 

arithmetic; if this interval includes 0, then fall back to 

exact computation (which can be very slow). 

 

EXAMPLES:: 

 

sage: AA(-5).nth_root(7).sign() 

-1 

sage: (AA(2).sqrt() - AA(2).sqrt()).sign() 

0 

 

sage: a = AA(2).sqrt() + AA(3).sqrt() - 58114382797550084497/18470915334626475921 

sage: a.sign() 

1 

sage: b = AA(2).sqrt() + AA(3).sqrt() - 2602510228533039296408/827174681630786895911 

sage: b.sign() 

-1 

 

sage: c = AA(5)**(1/3) - 1437624125539676934786/840727688792155114277 

sage: c.sign() 

1 

 

sage: (((a+b)*(a+c)*(b+c))**9 / (a*b*c)).sign() 

1 

sage: (a-b).sign() 

1 

sage: (b-a).sign() 

-1 

sage: (a*b).sign() 

-1 

sage: ((a*b).abs() + a).sign() 

1 

sage: (a*b - b*a).sign() 

0 

""" 

if not self._value.contains_zero(): 

return self._value.unique_sign() 

 

sd = self._descr 

if isinstance(self._descr, ANRational): 

return sd._value.sign() 

elif isinstance(self._descr, ANExtensionElement): 

# All field elements are irrational by construction 

# (the ANExtensionElement constructor will return an ANRational 

# instead, if the number is actually rational). 

# An irrational number must eventually be different from 0 

while self._value.contains_zero(): 

self._more_precision() 

return self._value.unique_sign() 

elif type(sd) is ANBinaryExpr: 

ls = sd._left.sign() 

rs = sd._right.sign() 

if sd._op is operator.mul or sd._op is operator.truediv: 

return sd._left.sign() * sd._right.sign() 

elif sd._op is operator.add: 

if ls == rs: 

return ls 

else: 

if ls == -rs: 

return ls 

elif not ls: 

self._set_descr((-sd._right)._descr) 

return -rs 

elif not rs: 

self._set_descr(sd._left._descr) 

return ls 

elif type(sd) is ANUnaryExpr: 

if sd._op == 'abs': 

c = 1 if bool(sd._arg) else 0 

if not c: 

self._set_descr(ANRational(QQ.zero())) 

return c 

elif sd._op == '-': 

return -(sd._arg.sign()) 

elif sd._op == '~': 

return sd._arg.sign() 

 

if self._value.prec() < 128: 

# OK, we'll try adding precision one more time 

self._more_precision() 

if not self._value.contains_zero(): 

return self._value.unique_sign() 

 

# Sigh... 

self.exactify() 

return self.sign() 

 

def _interval_fast(self, prec): 

r""" 

Compute an approximation to this ``AlgebraicReal`` object in a real interval field of precision prec. 

 

EXAMPLES:: 

 

sage: t = AA(sqrt(7)) 

sage: t._interval_fast(100) 

2.64575131106459059050161575364? 

""" 

return self.interval_fast(RealIntervalField(prec)) 

 

def interval_exact(self, field): 

""" 

Given a ``RealIntervalField``, compute the best possible 

approximation of this number in that field. Note that if this 

number is sufficiently close to some floating-point number 

(and, in particular, if this number is exactly representable in 

floating-point), then this will trigger exact computation, which 

may be very slow. 

 

EXAMPLES:: 

 

sage: x = AA(2).sqrt() 

sage: y = x*x 

sage: x.interval(RIF) 

1.414213562373095? 

sage: x.interval_exact(RIF) 

1.414213562373095? 

sage: y.interval(RIF) 

2.000000000000000? 

sage: y.interval_exact(RIF) 

2 

sage: z = 1 + AA(2).sqrt() / 2^200 

sage: z.interval(RIF) 

1.000000000000001? 

sage: z.interval_exact(RIF) 

1.000000000000001? 

""" 

for extra in (0, 40): 

target = RR(1.0) >> field.prec() 

# p==precise; pr==precise rounded 

pval = self.interval_diameter(target) 

pbot = pval.lower() 

ptop = pval.upper() 

val = field(pval) 

bot = val.lower() 

top = val.upper() 

prbot = pbot.parent()(bot) 

prtop = ptop.parent()(top) 

if bot == top or (bot.nextabove() == top and 

prbot < pbot and ptop < prtop): 

return val 

 

# Even 40 extra bits of precision aren't enough to prove that 

# self is not an exactly representable float. 

self.exactify() 

while True: 

# p==precise; pr==precise rounded 

pval = self._value 

pbot = pval.lower() 

ptop = pval.upper() 

val = field(pval) 

bot = val.lower() 

top = val.upper() 

prbot = pbot.parent()(bot) 

prtop = ptop.parent()(top) 

if bot == top or (bot.nextabove() == top and 

prbot < pbot and ptop < prtop): 

return val 

 

self._more_precision() 

 

def real_number(self, field): 

""" 

Given a ``RealField``, compute a good approximation to self in 

that field. The approximation will be off by at most two 

ulp's, except for numbers which are very close to 0, which 

will have an absolute error at most 

``2**(-(field.prec()-1))``. Also, the rounding mode of the 

field is respected. 

 

EXAMPLES:: 

 

sage: x = AA(2).sqrt()^2 

sage: x.real_number(RR) 

2.00000000000000 

sage: x.real_number(RealField(53, rnd='RNDD')) 

1.99999999999999 

sage: x.real_number(RealField(53, rnd='RNDU')) 

2.00000000000001 

sage: x.real_number(RealField(53, rnd='RNDZ')) 

1.99999999999999 

sage: (-x).real_number(RR) 

-2.00000000000000 

sage: (-x).real_number(RealField(53, rnd='RNDD')) 

-2.00000000000001 

sage: (-x).real_number(RealField(53, rnd='RNDU')) 

-1.99999999999999 

sage: (-x).real_number(RealField(53, rnd='RNDZ')) 

-1.99999999999999 

sage: (x-2).real_number(RR) 

5.42101086242752e-20 

sage: (x-2).real_number(RealField(53, rnd='RNDD')) 

-1.08420217248551e-19 

sage: (x-2).real_number(RealField(53, rnd='RNDU')) 

2.16840434497101e-19 

sage: (x-2).real_number(RealField(53, rnd='RNDZ')) 

0.000000000000000 

sage: y = AA(2).sqrt() 

sage: y.real_number(RR) 

1.41421356237309 

sage: y.real_number(RealField(53, rnd='RNDD')) 

1.41421356237309 

sage: y.real_number(RealField(53, rnd='RNDU')) 

1.41421356237310 

sage: y.real_number(RealField(53, rnd='RNDZ')) 

1.41421356237309 

""" 

v = self.interval(RealIntervalField(field.prec())) 

return field(v) 

 

_mpfr_ = real_number 

 

def __float__(self): 

r""" 

Compute a good float approximation to self. 

 

EXAMPLES:: 

 

sage: AA(golden_ratio).__float__() 

1.618033988749895 

sage: float(AA(sqrt(11))) 

3.3166247903554 

""" 

return float(RR(self)) 

 

def _complex_mpfr_field_(self, field): 

r""" 

Compute an approximation to this ``AlgebraicReal`` in the given field, 

which may be an interval field (in which case ``self.interval()`` is 

called) or any other real number field (in which case 

``self.real_number()`` is called. 

 

Note that the field ``field`` should be a *complex* field (whose 

``_real_field()`` method will be called to obtain a real subfield.) 

 

EXAMPLES:: 

 

sage: AA(golden_ratio)._complex_mpfr_field_(ComplexIntervalField(100)) 

1.618033988749894848204586834365? 

sage: AA(golden_ratio)._complex_mpfr_field_(ComplexField(100)) 

1.6180339887498948482045868344 

""" 

if is_ComplexIntervalField(field): 

return field(self.interval(field._real_field())) 

else: 

return field(self.real_number(field._real_field())) 

 

def real_exact(self, field): 

r""" 

Given a ``RealField``, compute the best possible approximation of 

this number in that field. Note that if this number is 

sufficiently close to the halfway point between two 

floating-point numbers in the field (for the default 

round-to-nearest mode) or if the number is sufficiently close 

to a floating-point number in the field (for directed rounding 

modes), then this will trigger exact computation, which may be 

very slow. 

 

The rounding mode of the field is respected. 

 

EXAMPLES:: 

 

sage: x = AA(2).sqrt()^2 

sage: x.real_exact(RR) 

2.00000000000000 

sage: x.real_exact(RealField(53, rnd='RNDD')) 

2.00000000000000 

sage: x.real_exact(RealField(53, rnd='RNDU')) 

2.00000000000000 

sage: x.real_exact(RealField(53, rnd='RNDZ')) 

2.00000000000000 

sage: (-x).real_exact(RR) 

-2.00000000000000 

sage: (-x).real_exact(RealField(53, rnd='RNDD')) 

-2.00000000000000 

sage: (-x).real_exact(RealField(53, rnd='RNDU')) 

-2.00000000000000 

sage: (-x).real_exact(RealField(53, rnd='RNDZ')) 

-2.00000000000000 

sage: y = (x-2).real_exact(RR).abs() 

sage: y == 0.0 or y == -0.0 # the sign of 0.0 is not significant in MPFI 

True 

sage: y = (x-2).real_exact(RealField(53, rnd='RNDD')) 

sage: y == 0.0 or y == -0.0 # same as above 

True 

sage: y = (x-2).real_exact(RealField(53, rnd='RNDU')) 

sage: y == 0.0 or y == -0.0 # idem 

True 

sage: y = (x-2).real_exact(RealField(53, rnd='RNDZ')) 

sage: y == 0.0 or y == -0.0 # ibidem 

True 

sage: y = AA(2).sqrt() 

sage: y.real_exact(RR) 

1.41421356237310 

sage: y.real_exact(RealField(53, rnd='RNDD')) 

1.41421356237309 

sage: y.real_exact(RealField(53, rnd='RNDU')) 

1.41421356237310 

sage: y.real_exact(RealField(53, rnd='RNDZ')) 

1.41421356237309 

""" 

for extra in (0, 40): 

target = RR(1.0) >> field.prec() 

val = self.interval_diameter(target) 

fbot = field(val.lower()) 

ftop = field(val.upper()) 

if fbot == ftop: 

return ftop 

 

# Even 40 extra bits of precision aren't enough to determine the 

# answer. 

rifp1 = RealIntervalField(field.prec() + 1) 

rifp2 = RealIntervalField(field.prec() + 2) 

 

val = self.interval_exact(rifp1) 

 

# Call the largest floating-point number <= self 'x'. Then 

# val may be [x .. x], [x .. x + 1/2 ulp], 

# [x + 1/2 ulp .. x + 1/2 ulp], or [x + 1/2 ulp .. x + 1 ulp]; 

# in the second and fourth cases, the true value is not equal 

# to either of the interval endpoints. 

 

mid = rifp2(val).center() 

 

# Now mid may be x, x + 1/4 ulp, x + 1/2 ulp, or x + 3/4 ulp; in 

# the first and third cases, mid is the exact, true value of self; 

# in the second and fourth cases, self is close to mid, and is 

# neither x, x + 1/2 ulp, nor x + 1 ulp. 

 

# In all of these cases, in all rounding modes, the rounded value 

# of mid is the same as the rounded value of self. 

 

return field(mid) 

 

 

class AlgebraicNumberPowQQAction(Action): 

""" 

Implement powering of an algebraic number (an element of ``QQbar`` 

or ``AA``) by a rational. 

 

This is always a right action. 

 

INPUT: 

 

- ``G`` -- must be ``QQ`` 

 

- ``S`` -- the parent on which to act, either ``AA`` or ``QQbar``. 

 

.. NOTE:: 

 

To compute ``x ^ (a/b)``, we take the `b`'th root of `x`; then 

we take that to the `a`'th power. If `x` is a negative algebraic 

real and `b` is odd, take the real `b`'th root; otherwise take 

the principal `b`'th root. 

 

EXAMPLES: 

 

In ``QQbar``:: 

 

sage: QQbar(2)^(1/2) 

1.414213562373095? 

sage: QQbar(8)^(2/3) 

4 

sage: QQbar(8)^(2/3) == 4 

True 

sage: x = polygen(QQbar) 

sage: phi = QQbar.polynomial_root(x^2 - x - 1, RIF(1, 2)) 

sage: tau = QQbar.polynomial_root(x^2 - x - 1, RIF(-1, 0)) 

sage: rt5 = QQbar(5)^(1/2) 

sage: phi^10 / rt5 

55.00363612324742? 

sage: tau^10 / rt5 

0.003636123247413266? 

sage: (phi^10 - tau^10) / rt5 

55.00000000000000? 

sage: (phi^10 - tau^10) / rt5 == fibonacci(10) 

True 

sage: (phi^50 - tau^50) / rt5 == fibonacci(50) 

True 

sage: QQbar(-8)^(1/3) 

1.000000000000000? + 1.732050807568878?*I 

sage: (QQbar(-8)^(1/3))^3 

-8 

sage: QQbar(32)^(1/5) 

2 

sage: a = QQbar.zeta(7)^(1/3); a 

0.9555728057861407? + 0.2947551744109043?*I 

sage: a == QQbar.zeta(21) 

True 

sage: QQbar.zeta(7)^6 

0.6234898018587335? - 0.7818314824680299?*I 

sage: (QQbar.zeta(7)^6)^(1/3) * QQbar.zeta(21) 

1.000000000000000? + 0.?e-17*I 

 

In ``AA``:: 

 

sage: AA(2)^(1/2) 

1.414213562373095? 

sage: AA(8)^(2/3) 

4 

sage: AA(8)^(2/3) == 4 

True 

sage: x = polygen(AA) 

sage: phi = AA.polynomial_root(x^2 - x - 1, RIF(0, 2)) 

sage: tau = AA.polynomial_root(x^2 - x - 1, RIF(-2, 0)) 

sage: rt5 = AA(5)^(1/2) 

sage: phi^10 / rt5 

55.00363612324742? 

sage: tau^10 / rt5 

0.003636123247413266? 

sage: (phi^10 - tau^10) / rt5 

55.00000000000000? 

sage: (phi^10 - tau^10) / rt5 == fibonacci(10) 

True 

sage: (phi^50 - tau^50) / rt5 == fibonacci(50) 

True 

 

TESTS:: 

 

sage: AA(-8)^(1/3) 

-2 

sage: AA(-8)^(2/3) 

4 

sage: AA(32)^(3/5) 

8 

sage: AA(-16)^(1/2) 

4*I 

sage: AA(-16)^(1/4) 

1.414213562373095? + 1.414213562373095?*I 

sage: AA(-16)^(1/4)/QQbar.zeta(8) 

2 

 

We check that :trac:`7859` is fixed:: 

 

sage: (AA(2)^(1/2)-AA(2)^(1/2))^(1/2) 

0 

""" 

def __init__(self, G, S): 

""" 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import AlgebraicNumberPowQQAction 

sage: act = AlgebraicNumberPowQQAction(QQ, AA); act 

Right Rational Powering by Rational Field on Algebraic Real Field 

sage: act(AA(-2), 1/3) 

-1.259921049894873? 

 

:: 

 

sage: act = AlgebraicNumberPowQQAction(QQ, QQbar); act 

Right Rational Powering by Rational Field on Algebraic Field 

sage: act(QQbar(-2), 1/3) 

0.6299605249474365? + 1.091123635971722?*I 

""" 

Action.__init__(self, G, S, False, operator.pow) 

 

def _call_(self, x, e): 

r""" 

Return the power ``x ^ e``. 

 

INPUT: 

 

- ``x`` -- an algebraic number 

 

- ``e`` -- a rational number 

""" 

if not x: 

return x 

 

n = e.numerator() 

d = e.denominator() 

if d == 1: 

return x._pow_int(n) 

 

# Parent of the result 

S = self.codomain() 

if S is AA and d % 2 == 0 and x.sign() < 0: 

S = QQbar 

 

# First, check for exact roots. 

if isinstance(x._descr, ANRational): 

rt = rational_exact_root(abs(x._descr._value), d) 

if rt is not None: 

if x._descr._value < 0: 

if S is AA: 

return AlgebraicReal(ANRational((-rt)**n)) 

else: 

z = QQbar.zeta(2*d)._pow_int(n) 

return z * AlgebraicNumber(ANRational(rt**n)) 

return S(ANRational(rt**n)) 

 

if S is AA: 

# Result lies in AA 

pow_n = x._pow_int(n) 

poly = AAPoly.gen()**d - pow_n 

range = pow_n.interval_fast(RIF) 

if d % 2 == 0: 

result_min = 0 

else: 

result_min = min(range.lower(), -1) 

result_max = max(range.upper(), 1) 

return AlgebraicReal(ANRoot(poly, RIF(result_min, result_max))) 

 

# Result lies in QQbar 

 

# Determine whether arg(x) equals pi. 

argument_is_pi = False 

for prec in short_prec_seq(): 

if prec is None: 

# We know that x.real() < 0, since x._value 

# crosses the negative real line and x._value 

# is known to be non-zero. 

isgn = x.imag().sign() 

val = x._value 

argument = val.argument() 

if isgn == 0: 

argument = argument.parent().pi() 

argument_is_pi = True 

elif isgn > 0: 

if argument < 0: 

argument = argument + 2 * argument.parent().pi() 

else: 

if argument > 0: 

argument = argument - 2 * argument.parent().pi() 

else: 

val = x._interval_fast(prec) 

if is_RealIntervalFieldElement(val) or not val.crosses_log_branch_cut(): 

argument = val.argument() 

if val.imag().is_zero() and val.real() < 0: 

argument_is_pi = True 

break 

 

target_abs = abs(val) ** e 

target_arg = argument * e 

 

for prec in tail_prec_seq(): 

if target_abs.relative_diameter() < RR_1_10 and (target_arg * d).absolute_diameter() < RR_1_10: 

break 

 

val = x._interval_fast(prec) 

 

target_abs = abs(val) ** e 

argument = val.argument() 

if argument_is_pi: 

argument = argument.parent().pi() 

target_arg = argument * e 

 

pow_n = x**n 

poly = QQbarPoly.gen()**d - pow_n 

 

prec = target_abs.prec() 

if argument_is_pi and d == 2: 

target_real = 0 

else: 

target_real = target_arg.cos() * target_abs 

target = ComplexIntervalField(prec)(target_real, 

target_arg.sin() * target_abs) 

 

return AlgebraicNumber(ANRoot(poly, target)) 

 

def _repr_name_(self): 

return "Rational Powering" 

 

 

class ANRational(ANDescr): 

r""" 

The subclass of ``ANDescr`` that represents an arbitrary 

rational. This class is private, and should not be used directly. 

""" 

 

def __init__(self, x): 

""" 

TESTS:: 

 

sage: polygen(QQbar) / int(3) 

1/3*x 

sage: QQbar(int(7)) / QQbar(long(2)) 

7/2 

""" 

if isinstance(x, (sage.rings.integer.Integer, 

sage.rings.rational.Rational)): 

self._value = x 

elif isinstance(x, integer_types): 

self._value = ZZ(x) 

else: 

raise TypeError("Illegal initializer for algebraic number rational") 

 

def __reduce__(self): 

""" 

Add customized pickling support. 

 

EXAMPLES:: 

 

sage: t = AA(5/2); type(t._descr) 

<class 'sage.rings.qqbar.ANRational'> 

sage: loads(dumps(t)) == t 

True 

""" 

return (ANRational, (self._value, )) 

 

def _repr_(self): 

r""" 

String representation of self. 

 

EXAMPLES:: 

 

sage: QQbar(2/3)._repr_() 

'2/3' 

""" 

return repr(self._value) 

 

def handle_sage_input(self, sib, coerce, is_qqbar): 

r""" 

Produce an expression which will reproduce this value when evaluated, 

and an indication of whether this value is worth sharing (always 

False, for rationals). 

 

EXAMPLES:: 

 

sage: sage_input(QQbar(22/7), verify=True) 

# Verified 

QQbar(22/7) 

sage: sage_input(-AA(3)/5, verify=True) 

# Verified 

AA(-3/5) 

sage: sage_input(vector(AA, (0, 1/2, 1/3)), verify=True) 

# Verified 

vector(AA, [0, 1/2, 1/3]) 

sage: from sage.rings.qqbar import * 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: rat = ANRational(9/10) 

sage: rat.handle_sage_input(sib, False, True) 

({call: {atomic:QQbar}({binop:/ {atomic:9} {atomic:10}})}, False) 

""" 

v = sib(self._value, True) 

if not coerce: 

v = sib.name('QQbar' if is_qqbar else 'AA')(v) 

return (v, False) 

 

def _interval_fast(self, prec): 

r""" 

Return an approximation to self in a real interval field of precision prec. 

 

EXAMPLES:: 

 

sage: QQbar(355/113)._descr._interval_fast(30) 

3.14159292? 

""" 

return RealIntervalField(prec)(self._value) 

 

def generator(self): 

r""" 

Return an :class:`AlgebraicGenerator` object associated to this 

element. Returns the trivial generator, since self is rational. 

 

EXAMPLES:: 

 

sage: QQbar(0)._descr.generator() 

Trivial generator 

""" 

return qq_generator 

 

def is_complex(self): 

r""" 

Return False, since rational numbers are real 

 

EXAMPLES:: 

 

sage: QQbar(1/7)._descr.is_complex() 

False 

""" 

return False 

 

def exactify(self): 

r""" 

Calculate self exactly. Since self is a rational number, return self. 

 

EXAMPLES:: 

 

sage: a = QQbar(1/3)._descr 

sage: a.exactify() is a 

True 

""" 

return self 

 

def is_simple(self): 

""" 

Checks whether this descriptor represents a value with the same 

algebraic degree as the number field associated with the descriptor. 

 

This is always true for rational numbers. 

 

EXAMPLES:: 

 

sage: AA(1/2)._descr.is_simple() 

True 

""" 

return True 

 

def minpoly(self): 

r""" 

Return the min poly of self over `\QQ`. 

 

EXAMPLES:: 

 

sage: QQbar(7)._descr.minpoly() 

x - 7 

""" 

return QQx_x - self._value 

 

def neg(self, n): 

r""" 

Negation of self. 

 

EXAMPLES:: 

 

sage: a = QQbar(3) 

sage: b = a._descr 

sage: type(b) 

<class 'sage.rings.qqbar.ANRational'> 

sage: b.neg(a) 

-3 

""" 

return ANRational(-self._value) 

 

def invert(self, n): 

r""" 

1/self. 

 

EXAMPLES:: 

 

sage: a = QQbar(3) 

sage: b = a._descr 

sage: b.invert(a) 

1/3 

""" 

return ANRational(~self._value) 

 

def abs(self, n): 

r""" 

Absolute value of self. 

 

EXAMPLES:: 

 

sage: a = QQbar(3) 

sage: b = a._descr 

sage: b.abs(a) 

3 

""" 

return ANRational(abs(self._value)) 

 

def rational_argument(self, n): 

r""" 

Return the argument of self divided by `2 \pi`, or ``None`` if this 

element is 0. 

 

EXAMPLES:: 

 

sage: QQbar(3)._descr.rational_argument(None) 

0 

sage: QQbar(-3)._descr.rational_argument(None) 

1/2 

sage: QQbar(0)._descr.rational_argument(None) is None 

True 

""" 

if self._value > 0: 

return QQ(0) 

if self._value < 0: 

return QQ(1)/2 

return None 

 

def angle(self): 

r""" 

Return a rational number `q \in (-1/2, 1/2]` such that ``self`` is a rational multiple of 

`e^{2\pi i q}`. Always returns 0, since this element is rational. 

 

EXAMPLES:: 

 

sage: QQbar(3)._descr.angle() 

0 

sage: QQbar(-3)._descr.angle() 

0 

sage: QQbar(0)._descr.angle() 

0 

""" 

return QQ_0 

 

def scale(self): 

r""" 

Return a rational number `r` such that ``self`` is equal to `r e^{2 \pi 

i q}` for some `q \in (-1/2, 1/2]`. In other words, just return self 

as a rational number. 

 

EXAMPLES:: 

 

sage: QQbar(-3)._descr.scale() 

-3 

""" 

return self._value 

 

def is_AlgebraicReal(x): 

r""" 

Test if ``x`` is an instance of :class:`~AlgebraicReal`. For internal use. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import is_AlgebraicReal 

sage: is_AlgebraicReal(AA(sqrt(2))) 

True 

sage: is_AlgebraicReal(QQbar(sqrt(2))) 

False 

sage: is_AlgebraicReal("spam") 

False 

""" 

return isinstance(x, AlgebraicReal) 

 

def is_AlgebraicNumber(x): 

r""" 

Test if ``x`` is an instance of :class:`~AlgebraicNumber`. For internal use. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import is_AlgebraicNumber 

sage: is_AlgebraicNumber(AA(sqrt(2))) 

False 

sage: is_AlgebraicNumber(QQbar(sqrt(2))) 

True 

sage: is_AlgebraicNumber("spam") 

False 

""" 

return isinstance(x, AlgebraicNumber) 

 

QQbarPoly = PolynomialRing(QQbar, 'x') 

AAPoly = PolynomialRing(AA, 'x') 

 

class AlgebraicPolynomialTracker(SageObject): 

r""" 

Keeps track of a polynomial used for algebraic numbers. 

 

If multiple algebraic numbers are created as roots of a single 

polynomial, this allows the polynomial and information about 

the polynomial to be shared. This reduces work if the polynomial 

must be recomputed at higher precision, or if it must be factored. 

 

This class is private, and should only be constructed by 

``AA.common_polynomial()`` or ``QQbar.common_polynomial()``, and should 

only be used as an argument to ``AA.polynomial_root()`` or 

``QQbar.polynomial_root()``. (It doesn't matter whether you create 

the common polynomial with ``AA.common_polynomial()`` or 

``QQbar.common_polynomial()``.) 

 

EXAMPLES:: 

 

sage: x = polygen(QQbar) 

sage: P = QQbar.common_polynomial(x^2 - x - 1) 

sage: P 

x^2 - x - 1 

sage: QQbar.polynomial_root(P, RIF(1, 2)) 

1.618033988749895? 

""" 

 

def __init__(self, poly): 

r""" 

Initialize this AlgebraicPolynomialTracker object. 

 

EXAMPLES:: 

 

sage: x = polygen(QQbar) 

sage: P = QQbar.common_polynomial(x^2 - x - 1) 

sage: type(P) # indirect doctest 

<class 'sage.rings.qqbar.AlgebraicPolynomialTracker'> 

""" 

if not is_Polynomial(poly): 

raise ValueError("Trying to create AlgebraicPolynomialTracker on non-Polynomial") 

if isinstance(poly.base_ring(), AlgebraicField_common): 

complex = is_AlgebraicField(poly.base_ring()) 

else: 

try: 

poly = poly.change_ring(AA) 

complex = False 

except (TypeError, ValueError): 

poly = poly.change_ring(QQbar) 

complex = True 

self._poly = poly 

self._complex = complex 

self._exact = False 

self._roots_cache = {} 

 

def __reduce__(self): 

""" 

Add customized pickling support. 

 

EXAMPLES:: 

 

sage: x = polygen(QQ) 

sage: v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1] 

sage: type(v._descr._poly) 

<class 'sage.rings.qqbar.AlgebraicPolynomialTracker'> 

sage: loads(dumps(v)) == v 

True 

""" 

return (AlgebraicPolynomialTracker, (self._poly, )) 

 

def _sage_input_(self, sib, coerce): 

r""" 

Produce an expression which will reproduce this value when evaluated. 

 

EXAMPLES:: 

 

sage: x = polygen(QQ) 

sage: sage_input(AA.common_polynomial(x^3 - 7)) 

R.<x> = AA[] 

AA.common_polynomial(x^3 - 7) 

sage: x = polygen(AA) 

sage: p = sqrt(AA(2)) * x^2 - sqrt(AA(3)) 

sage: cp = AA.common_polynomial(p) 

sage: sage_input((cp, cp)) 

R.<x> = AA[] 

cp = AA.common_polynomial(AA.polynomial_root(AA.common_polynomial(x^2 - 2), RIF(RR(1.4142135623730949), RR(1.4142135623730951)))*x^2 - AA.polynomial_root(AA.common_polynomial(x^2 - 3), RIF(RR(1.7320508075688772), RR(1.7320508075688774)))) 

(cp, cp) 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: cp._sage_input_(sib, False) 

{call: {getattr: {atomic:AA}.common_polynomial}({binop:- {binop:* {call: {getattr: {atomic:AA}.polynomial_root}({call: {getattr: {atomic:AA}.common_polynomial}({binop:- {binop:** {gen:x {constr_parent: {subscr: {atomic:AA}[{atomic:'x'}]} with gens: ('x',)}} {atomic:2}} {atomic:2}})}, {call: {atomic:RIF}({call: {atomic:RR}({atomic:1.4142135623730949})}, {call: {atomic:RR}({atomic:1.4142135623730951})})})} {binop:** {gen:x {constr_parent: {subscr: {atomic:AA}[{atomic:'x'}]} with gens: ('x',)}} {atomic:2}}} {call: {getattr: {atomic:AA}.polynomial_root}({call: {getattr: {atomic:AA}.common_polynomial}({binop:- {binop:** {gen:x {constr_parent: {subscr: {atomic:AA}[{atomic:'x'}]} with gens: ('x',)}} {atomic:2}} {atomic:3}})}, {call: {atomic:RIF}({call: {atomic:RR}({atomic:1.7320508075688772})}, {call: {atomic:RR}({atomic:1.7320508075688774})})})}})} 

""" 

# XXX It would be nicer to skip the "AA.common_polynomial()" 

# wrapper if the polynomial is not actually shared. But 

# sage_input.py isn't quite that generic. 

v = sib.name('AA').common_polynomial(self._poly) 

sib.id_cache(self, v, 'cp') 

return v 

 

def _repr_(self): 

r""" 

String representation of self. 

 

EXAMPLES:: 

 

sage: x = polygen(QQ) 

sage: AA.common_polynomial(x^3 - 7)._repr_() 

'x^3 - 7' 

""" 

return repr(self._poly) 

 

def poly(self): 

r""" 

Return the underlying polynomial of self. 

 

EXAMPLES:: 

 

sage: x = polygen(QQ); f = x^3 - 7 

sage: g = AA.common_polynomial(f) 

sage: g.poly() == f 

True 

""" 

return self._poly 

 

def is_complex(self): 

r""" 

Return True if the coefficients of this polynomial are non-real. 

 

EXAMPLES:: 

 

sage: x = polygen(QQ); f = x^3 - 7 

sage: g = AA.common_polynomial(f) 

sage: g.is_complex() 

False 

sage: QQbar.common_polynomial(x^3 - QQbar(I)).is_complex() 

True 

""" 

return self._complex 

 

def complex_roots(self, prec, multiplicity): 

""" 

Find the roots of self in the complex field to precision prec. 

 

EXAMPLES:: 

 

sage: x = polygen(ZZ) 

sage: cp = AA.common_polynomial(x^4 - 2) 

 

Note that the precision is not guaranteed to find the tightest 

possible interval since complex_roots() depends on the 

underlying BLAS implementation. :: 

 

sage: cp.complex_roots(30, 1) 

[-1.18920711500272...?, 

1.189207115002721?, 

-1.189207115002721?*I, 

1.189207115002721?*I] 

""" 

if multiplicity in self._roots_cache: 

roots = self._roots_cache[multiplicity] 

if roots[0] >= prec: 

return roots[1] 

 

p = self._poly 

for i in range(multiplicity - 1): 

p = p.derivative() 

 

from sage.rings.polynomial.complex_roots import complex_roots 

roots_mult = complex_roots(p, min_prec=prec) 

roots = [rt for (rt, mult) in roots_mult if mult == 1] 

self._roots_cache[multiplicity] = (prec, roots) 

return roots 

 

def exactify(self): 

""" 

Compute a common field that holds all of the algebraic coefficients 

of this polynomial, then factor the polynomial over that field. 

Store the factors for later use (ignoring multiplicity). 

 

EXAMPLES:: 

 

sage: x = polygen(AA) 

sage: p = sqrt(AA(2)) * x^2 - sqrt(AA(3)) 

sage: cp = AA.common_polynomial(p) 

sage: cp._exact 

False 

sage: cp.exactify() 

sage: cp._exact 

True 

""" 

if self._exact: 

return 

 

self._exact = True 

 

gen = qq_generator 

 

for c in self._poly.list(): 

c.exactify() 

gen = gen.union(c._exact_field()) 

 

self._gen = gen 

 

coeffs = [gen(c._exact_value()) for c in self._poly.list()] 

 

if gen.is_trivial(): 

qp = QQy(coeffs) 

self._factors = [fac_exp[0] for fac_exp in qp.factor()] 

else: 

fld = gen.field() 

fld_poly = fld['x'] 

 

fp = fld_poly(coeffs) 

 

self._factors = [fac_exp[0] for fac_exp in fp.factor()] 

 

def factors(self): 

r""" 

EXAMPLES:: 

 

sage: x=polygen(QQ); f=QQbar.common_polynomial(x^4 + 4) 

sage: f.factors() 

[y^2 - 2*y + 2, y^2 + 2*y + 2] 

""" 

self.exactify() 

return self._factors 

 

def generator(self): 

r""" 

Return an :class:`AlgebraicGenerator` for a number field containing all 

the coefficients of self. 

 

EXAMPLES:: 

 

sage: x = polygen(AA) 

sage: p = sqrt(AA(2)) * x^2 - sqrt(AA(3)) 

sage: cp = AA.common_polynomial(p) 

sage: cp.generator() 

Number Field in a with defining polynomial y^4 - 4*y^2 + 1 with a in 1.931851652578137? 

""" 

self.exactify() 

return self._gen 

 

class ANRoot(ANDescr): 

""" 

The subclass of ``ANDescr`` that represents a particular 

root of a polynomial with algebraic coefficients. 

This class is private, and should not be used directly. 

""" 

def __init__(self, poly, interval, multiplicity=1): 

r""" 

Initialize this ``ANRoot`` object. 

 

EXAMPLES:: 

 

sage: x = polygen(QQ); f = (x^3 + x + 1).roots(AA,multiplicities=False)[0]._descr 

sage: type(f) # indirect doctest 

<class 'sage.rings.qqbar.ANRoot'> 

""" 

if not isinstance(poly, AlgebraicPolynomialTracker): 

poly = AlgebraicPolynomialTracker(poly) 

self._poly = poly 

self._multiplicity = multiplicity 

self._complex = is_ComplexIntervalFieldElement(interval) 

self._complex_poly = poly.is_complex() 

self._interval = self.refine_interval(interval, 64) 

 

def __reduce__(self): 

""" 

Add customized pickling support. 

 

EXAMPLES:: 

 

sage: x = polygen(QQ) 

sage: v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1] 

sage: type(v._descr) 

<class 'sage.rings.qqbar.ANRoot'> 

sage: loads(dumps(v)) == v 

True 

""" 

return (ANRoot, (self._poly, self._interval, self._multiplicity)) 

 

def _repr_(self): 

r""" 

String representation of self. 

 

EXAMPLES:: 

 

sage: x=polygen(QQ); v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1] 

sage: v._descr._repr_() 

'Root 1.618033988749894849? of x^2 - x - 1' 

""" 

return 'Root %s of %s'%(self._interval, self._poly) 

 

def handle_sage_input(self, sib, coerce, is_qqbar): 

r""" 

Produce an expression which will reproduce this value when evaluated, 

and an indication of whether this value is worth sharing (always True, 

for ``ANRoot``). 

 

EXAMPLES:: 

 

sage: sage_input((AA(3)^(1/2))^(1/3), verify=True) 

# Verified 

R.<x> = AA[] 

AA.polynomial_root(AA.common_polynomial(x^3 - AA.polynomial_root(AA.common_polynomial(x^2 - 3), RIF(RR(1.7320508075688772), RR(1.7320508075688774)))), RIF(RR(1.2009369551760025), RR(1.2009369551760027))) 

 

These two examples are too big to verify quickly. (Verification 

would create a field of degree 28.):: 

 

sage: sage_input((sqrt(AA(3))^(5/7))^(9/4)) 

R.<x> = AA[] 

v1 = AA.polynomial_root(AA.common_polynomial(x^2 - 3), RIF(RR(1.7320508075688772), RR(1.7320508075688774))) 

v2 = v1*v1 

v3 = AA.polynomial_root(AA.common_polynomial(x^7 - v2*v2*v1), RIF(RR(1.4804728524798112), RR(1.4804728524798114))) 

v4 = v3*v3 

v5 = v4*v4 

AA.polynomial_root(AA.common_polynomial(x^4 - v5*v5*v3), RIF(RR(2.4176921938267877), RR(2.4176921938267881))) 

sage: sage_input((sqrt(QQbar(-7))^(5/7))^(9/4)) 

R.<x> = QQbar[] 

v1 = QQbar.polynomial_root(AA.common_polynomial(x^2 + 7), CIF(RIF(RR(0)), RIF(RR(2.6457513110645903), RR(2.6457513110645907)))) 

v2 = v1*v1 

v3 = QQbar.polynomial_root(AA.common_polynomial(x^7 - v2*v2*v1), CIF(RIF(RR(0.8693488875796217), RR(0.86934888757962181)), RIF(RR(1.8052215661454434), RR(1.8052215661454436)))) 

v4 = v3*v3 

v5 = v4*v4 

QQbar.polynomial_root(AA.common_polynomial(x^4 - v5*v5*v3), CIF(RIF(-RR(3.8954086044650791), -RR(3.8954086044650786)), RIF(RR(2.7639398015408925), RR(2.7639398015408929)))) 

sage: x = polygen(QQ) 

sage: sage_input(AA.polynomial_root(x^2-x-1, RIF(1, 2)), verify=True) 

# Verified 

R.<x> = AA[] 

AA.polynomial_root(AA.common_polynomial(x^2 - x - 1), RIF(RR(1.6180339887498947), RR(1.6180339887498949))) 

sage: sage_input(QQbar.polynomial_root(x^3-5, CIF(RIF(-3, 0), RIF(0, 3))), verify=True) 

# Verified 

R.<x> = AA[] 

QQbar.polynomial_root(AA.common_polynomial(x^3 - 5), CIF(RIF(-RR(0.85498797333834853), -RR(0.85498797333834842)), RIF(RR(1.4808826096823642), RR(1.4808826096823644)))) 

sage: from sage.rings.qqbar import * 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: rt = ANRoot(x^3 - 2, RIF(0, 4)) 

sage: rt.handle_sage_input(sib, False, True) 

({call: {getattr: {atomic:QQbar}.polynomial_root}({call: {getattr: {atomic:AA}.common_polynomial}({binop:- {binop:** {gen:x {constr_parent: {subscr: {atomic:AA}[{atomic:'x'}]} with gens: ('x',)}} {atomic:3}} {atomic:2}})}, {call: {atomic:RIF}({call: {atomic:RR}({atomic:1.259921049894873})}, {call: {atomic:RR}({atomic:1.2599210498948732})})})}, True) 

""" 

parent = sib.name('QQbar' if is_qqbar else 'AA') 

poly = sib(self._poly) 

intv = self._interval 

# Check whether a 53-bit interval actually isolates the root. 

# If so, use it, because 53-bit intervals print prettier. 

if is_ComplexIntervalFieldElement(intv): 

loose_intv = CIF(intv) 

else: 

loose_intv = RIF(intv) 

# If the derivative of the polynomial is bounded away from 0 

# over this interval, then it definitely isolates a root. 

if self._poly._poly.derivative()(loose_intv) != 0: 

good_intv = loose_intv 

else: 

good_intv = intv 

return (parent.polynomial_root(poly, sib(good_intv)), True) 

 

def is_complex(self): 

r""" 

Whether this is a root in `\overline{\QQ}` (rather than `\mathbf{A}`). 

Note that this may return True even if the root is actually real, as 

the second example shows; it does *not* trigger exact computation to 

see if the root is real. 

 

EXAMPLES:: 

 

sage: x = polygen(QQ) 

sage: (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.is_complex() 

False 

sage: (x^2 - x - 1).roots(ring=QQbar, multiplicities=False)[1]._descr.is_complex() 

True 

""" 

return self._complex 

 

def conjugate(self, n): 

r""" 

Complex conjugate of this ANRoot object. 

 

EXAMPLES:: 

 

sage: a = (x^2 + 23).roots(ring=QQbar, multiplicities=False)[0] 

sage: b = a._descr 

sage: type(b) 

<class 'sage.rings.qqbar.ANRoot'> 

sage: c = b.conjugate(a); c 

<sage.rings.qqbar.ANUnaryExpr object at ...> 

sage: c.exactify() 

-2*a + 1 where a^2 - a + 6 = 0 and a in 0.50000000000000000? - 2.397915761656360?*I 

""" 

if not self._complex: 

return self 

if not self._complex_poly: 

return ANRoot(self._poly, self._interval.conjugate(), self._multiplicity) 

 

return ANUnaryExpr(n, 'conjugate') 

 

def refine_interval(self, interval, prec): 

r""" 

Takes an interval which is assumed to enclose exactly one root 

of the polynomial (or, with multiplicity=`k`, exactly one root 

of the `k-1`-st derivative); and a precision, in bits. 

 

Tries to find a narrow interval enclosing the root using 

interval arithmetic of the given precision. (No particular 

number of resulting bits of precision is guaranteed.) 

 

Uses a combination of Newton's method (adapted for interval 

arithmetic) and bisection. The algorithm will converge very 

quickly if started with a sufficiently narrow interval. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import ANRoot 

sage: x = polygen(AA) 

sage: rt2 = ANRoot(x^2 - 2, RIF(0, 2)) 

sage: rt2.refine_interval(RIF(0, 2), 75) 

1.4142135623730950488017? 

""" 

if self._complex or self._complex_poly: 

v = self._complex_refine_interval(interval, prec) 

if self._complex: 

return v 

else: 

return v.real() 

else: 

return self._real_refine_interval(interval, prec) 

 

def _real_refine_interval(self, interval, prec): 

r""" 

Does the calculation for ``refine_interval``. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import ANRoot 

sage: x = polygen(AA) 

sage: rt2 = ANRoot(x^2 - 2, RIF(0, 2)) 

sage: rt2.refine_interval(RIF(0, 2), 75) # indirect doctest 

1.4142135623730950488017? 

""" 

# Don't throw away bits in the original interval; doing so might 

# invalidate it (include an extra root) 

 

field = RealIntervalField(max(prec, interval.prec())) 

interval = field(interval) 

if interval.is_exact(): 

return interval 

 

p = self._poly.poly() 

dp = p.derivative() 

for i in range(self._multiplicity - 1): 

p = dp 

dp = p.derivative() 

 

zero = field.zero() 

 

poly_ring = field['x'] 

 

# interval_p = poly_ring(p) 

coeffs = [c._interval_fast(prec) for c in p.list()] 

interval_p = poly_ring(coeffs) 

 

# This special case is important: this is the only way we could 

# refine "infinitely deep" (we could get an interval of diameter 

# about 2^{-2^31}, and then hit floating-point underflow); avoiding 

# this case here means we do not have to worry about iterating too 

# many times later 

if coeffs[0].is_zero() and interval.contains_zero(): 

return zero 

 

# interval_dp = poly_ring(dp) 

dcoeffs = [c.interval_fast(field) for c in dp.list()] 

interval_dp = poly_ring(dcoeffs) 

 

linfo = {} 

uinfo = {} 

 

def update_info(info, x): 

info['endpoint'] = x 

val = interval_p(field(x)) 

info['value'] = val 

# sign == 1 if val is bounded greater than 0 

# sign == -1 if val is bounded less than 0 

# sign == 0 if val might be 0 

if val > zero: 

info['sign'] = 1 

elif val < zero: 

info['sign'] = -1 

else: 

info['sign'] = 0 

 

update_info(linfo, interval.lower()) 

update_info(uinfo, interval.upper()) 

 

newton_lower = True 

 

while True: 

if linfo['sign'] == 0 and uinfo['sign'] == 0: 

# We take it on faith that there is a root in interval, 

# even though we can't prove it at the current precision. 

# We can't do any more refining... 

return interval 

 

if linfo['sign'] == uinfo['sign']: 

# Oops... 

raise ValueError("Refining interval that does not bound unique root!") 

 

# Use a simple algorithm: 

# Try an interval Newton-Raphson step. If this does not add at 

# least one bit of information, or if it fails (because the 

# slope is not bounded away from zero), then try bisection. 

# If this fails because the value at the midpoint is not 

# bounded away from zero, then also try the 1/4 and 3/4 points. 

# If all of these fail, then return the current interval. 

 

slope = interval_dp(interval) 

 

newton_success = False 

diam = interval.diameter() 

 

if not (zero in slope): 

# OK, we try Newton-Raphson. 

# I have no idea if it helps, but each time through the loop, 

# we either do Newton-Raphson from the left endpoint or 

# the right endpoint, alternating. 

 

newton_lower = not newton_lower 

if newton_lower: 

new_range = linfo['endpoint'] - linfo['value'] / slope 

else: 

new_range = uinfo['endpoint'] - uinfo['value'] / slope 

 

if new_range.lower() in interval: 

interval = field(new_range.lower(), interval.upper()) 

update_info(linfo, interval.lower()) 

if new_range.upper() in interval: 

interval = field(interval.lower(), new_range.upper()) 

update_info(uinfo, interval.upper()) 

 

new_diam = interval.diameter() 

 

if new_diam == 0: 

# Wow, we managed to find the answer exactly. 

# (I think this can only happen with a linear polynomial, 

# in which case we shouldn't have been in this 

# function at all; but oh well.) 

return interval 

 

if (new_diam << 1) <= diam: 

# We got at least one bit. 

newton_success = True 

 

if not newton_success: 

center = interval.center() 

 

def try_bisection(mid): 

minfo = {} 

update_info(minfo, mid) 

if minfo['sign'] == 0: 

return interval, False 

# We check to make sure the new interval is actually 

# narrower; this might not be true if the interval 

# is less than 4 ulp's wide 

if minfo['sign'] == linfo['sign'] and mid > interval.lower(): 

linfo['endpoint'] = minfo['endpoint'] 

linfo['value'] = minfo['value'] 

linfo['sign'] = minfo['sign'] 

return field(mid, interval.upper()), True 

if minfo['sign'] == uinfo['sign'] and mid < interval.upper(): 

uinfo['endpoint'] = minfo['endpoint'] 

uinfo['value'] = minfo['value'] 

uinfo['sign'] = minfo['sign'] 

return field(interval.lower(), mid), True 

return interval, False 

 

interval, bisect_success = try_bisection(center) 

 

if not bisect_success: 

uq = (center + interval.upper()) / 2 

interval, bisect_success = try_bisection(uq) 

if not bisect_success: 

lq = (center + interval.lower()) / 2 

interval, bisect_success = try_bisection(lq) 

 

if not bisect_success: 

# OK, we've refined about as much as we can. 

# (We might be able to trim a little more off the edges, 

# but the interval is no more than twice as wide as the 

# narrowest possible.) 

return interval 

 

def _complex_refine_interval(self, interval, prec): 

r""" 

Takes an interval which is assumed to enclose exactly one root 

of the polynomial (or, with multiplicity=`k`, exactly one root 

of the `k-1`-st derivative); and a precision, in bits. 

 

Tries to find a narrow interval enclosing the root using 

interval arithmetic of the given precision. (No particular 

number of resulting bits of precision is guaranteed.) 

 

Uses Newton's method (adapted for interval arithmetic). The 

algorithm will converge very quickly if started with a 

sufficiently narrow interval. If Newton's method fails, then 

we falls back on computing all the roots of the polynomial 

numerically, and select the appropriate root. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import ANRoot 

sage: x = polygen(QQbar) 

sage: intv = CIF(RIF(0, 1), RIF(0.1, 1)) 

sage: rt = ANRoot(x^5 - 1, intv) 

sage: new_intv = rt.refine_interval(intv, 53); new_intv # indirect doctest 

0.3090169943749474241? + 0.951056516295153573?*I 

sage: rt.refine_interval(new_intv, 70) 

0.30901699437494742411? + 0.95105651629515357212?*I 

""" 

# Don't throw away bits in the original interval; doing so might 

# invalidate it (include an extra root) 

 

field = ComplexIntervalField(max(prec, interval.prec())) 

interval = field(interval) 

if interval.is_exact(): 

return interval 

 

p = self._poly.poly() 

dp = p.derivative() 

for i in range(self._multiplicity - 1): 

p = dp 

dp = p.derivative() 

 

zero = field.zero() 

 

poly_ring = field['x'] 

 

# interval_p = poly_ring(p) 

coeffs = [c.interval_fast(field) for c in p.list()] 

interval_p = poly_ring(coeffs) 

 

# This special case is important: this is the only way we could 

# refine "infinitely deep" (we could get an interval of diameter 

# about 2^{-2^31}, and then hit floating-point underflow); avoiding 

# this case here means we do not have to worry about iterating too 

# many times later 

if coeffs[0].is_zero() and zero in interval: 

return zero 

 

# interval_dp = poly_ring(dp) 

dcoeffs = [c.interval_fast(field) for c in dp.list()] 

interval_dp = poly_ring(dcoeffs) 

 

while True: 

center = field(interval.center()) 

val = interval_p(center) 

 

slope = interval_dp(interval) 

 

diam = interval.diameter() 

 

if zero in slope: 

# Give up and fall back on root isolation. 

return self._complex_isolate_interval(interval, prec) 

 

if not (zero in slope): 

new_range = center - val / slope 

interval = interval.intersection(new_range) 

 

new_diam = interval.diameter() 

 

if new_diam == 0: 

# Wow; we nailed it exactly. (This may happen 

# whenever the root is exactly equal to some 

# floating-point number, and cannot happen 

# if the root is not equal to a floating-point 

# number.) We just return the perfect answer. 

return interval 

 

if new_diam == diam: 

# We're not getting any better. There are two 

# possible reasons for this. Either we have 

# refined as much as possible given the imprecision 

# of our interval polynomial, and we have the best 

# answer we're going to get at this precision; 

# or we started with a poor approximation to the 

# root, resulting in a broad range of possible 

# slopes in this interval, and Newton-Raphson refining 

# is not going to help. 

 

# I do not have a formal proof, but I believe the 

# following test differentiates between these two 

# behaviors. (If I'm wrong, we might get bad behavior 

# like infinite loops, but we still won't actually 

# return a wrong answer.) 

 

if val.contains_zero(): 

# OK, center must be a good approximation 

# to the root (in the current precision, anyway). 

# And the expression "center - val / slope" 

# above means that we have a pretty good interval, 

# even if slope is a poor estimate. 

return interval 

 

# The center of the current interval is known 

# not to be a root. This should let us divide 

# the interval in half, and improve on our previous 

# estimates. I can only think of two reasons why 

# it might not: 

# 1) the "center" of the interval is actually 

# on one of the edges of the interval (because the 

# interval is only one ulp wide), or 

# 2) the slope estimate is so bad that 

# "center - val / slope" doesn't give us information. 

 

# With complex intervals implemented as 

# rectangular regions of the complex plane, it's 

# possible that "val / slope" includes zero even 

# if both "val" and "slope" are bounded away from 

# zero, if the diameter of the (interval) argument 

# of val or slope is large enough. 

 

# So we test the diameter of the argument of 

# slope; if it's small, we decide that we must 

# have a good interval, but if it's big, we decide 

# that we probably can't make progress with 

# Newton-Raphson. 

 

# I think the relevant measure of "small" is 

# whether the diameter is less than pi/2; in that 

# case, no matter the value of "val" (as long as 

# "val" is fairly precise), "val / slope" should 

# be bounded away from zero. But we compare 

# against 1 instead, in the hopes that this might 

# be slightly faster. 

 

if slope.argument().absolute_diameter() < 1: 

return interval 

 

# And now it's time to give up. 

return self._complex_isolate_interval(interval, prec) 

 

def _complex_isolate_interval(self, interval, prec): 

""" 

Find a precise approximation to the unique root in interval, 

by finding a precise approximation to all roots of the 

polynomial, and checking which one is in interval. Slow but sure. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import ANRoot 

sage: x = polygen(QQbar) 

sage: intv = CIF(RIF(0, 1), RIF(0.1, 1)) 

sage: rt = ANRoot(x^5 - 1, intv) 

sage: rt._complex_isolate_interval(intv, 53) 

0.3090169943749474241? + 0.951056516295153573?*I 

""" 

rts = self._poly.complex_roots(prec, self._multiplicity) 

 

# Find all the roots that overlap interval. 

our_root = [rt for rt in rts if rt.overlaps(interval)] 

 

if len(our_root) == 1: 

return our_root[0] 

 

if len(our_root) == 0: 

raise ValueError("Complex root interval does not include any roots") 

 

# We have more than one root that overlap the current interval. 

# Technically, this might not be an error; perhaps the actual 

# root is just outside our interval, even though the (presumably 

# tight) interval containing that root touches our interval. 

 

# But it seems far more likely that the provided interval is 

# just too big. 

 

raise ValueError("Complex root interval probably includes multiple roots") 

 

def exactify(self): 

""" 

Returns either an ``ANRational`` or an 

``ANExtensionElement`` with the same value as this number. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import ANRoot 

sage: x = polygen(QQbar) 

sage: two = ANRoot((x-2)*(x-sqrt(QQbar(2))), RIF(1.9, 2.1)) 

sage: two.exactify() 

2 

sage: strange = ANRoot(x^2 + sqrt(QQbar(3))*x - sqrt(QQbar(2)), RIF(-0, 1)) 

sage: strange.exactify() 

a where a^8 - 6*a^6 + 5*a^4 - 12*a^2 + 4 = 0 and a in 0.6051012265139511? 

 

TESTS: 

 

Verify that :trac:`12727` is fixed:: 

 

sage: m = sqrt(sin(pi/5)); a = QQbar(m); b = AA(m) 

sage: a.minpoly() 

x^8 - 5/4*x^4 + 5/16 

sage: b.minpoly() 

x^8 - 5/4*x^4 + 5/16 

""" 

gen = self._poly.generator() 

 

if gen.is_trivial(): 

qpf = self._poly.factors() 

def find_fn(factor, prec): 

return factor(self._interval_fast(prec)) 

my_factor = find_zero_result(find_fn, qpf) 

 

# Factoring always returns monic polynomials over the rationals 

assert(my_factor.is_monic()) 

 

if my_factor.degree() == 1: 

return ANRational(-my_factor[0]) 

 

den, my_factor = clear_denominators(my_factor) 

 

red_elt, red_back, red_pol = do_polred(my_factor) 

 

field = NumberField(red_pol, 'a', check=False) 

 

def intv_fn(rif): 

return conjugate_expand(red_elt(self._interval_fast(rif) * den)) 

new_intv = conjugate_shrink(isolating_interval(intv_fn, red_pol)) 

root = ANRoot(QQx(red_pol), new_intv) 

new_gen = AlgebraicGenerator(field, root) 

 

return ANExtensionElement(new_gen, red_back(field.gen())/den) 

else: 

fld = gen.field() 

 

fpf = self._poly.factors() 

 

def find_fn(factor, prec): 

# XXX 

ifield = (ComplexIntervalField if self.is_complex() else RealIntervalField)(prec) 

if_poly = ifield['x'] 

gen_val = gen._interval_fast(prec) 

self_val = self._interval_fast(prec) 

v = [c.polynomial()(gen_val) for c in factor] 

# This try/except can be triggered if ifield is Real 

# but the entries in v have some imaginary part that 

# is only known to be 0 to very low precision, e.g., 

# as in Trac #12727. In such cases, we instead create 

# the polynomial over the appropriate complex interval 

# field, which is mathematically safe, unlike taking 

# real parts would be. 

try: 

ip = if_poly(v) 

except TypeError: 

if_poly = ComplexIntervalField(prec)['x'] 

ip = if_poly(v) 

return ip(self_val) 

my_factor = find_zero_result(find_fn, fpf) 

 

assert(my_factor.is_monic()) 

 

if my_factor.degree() == 1: 

return ANExtensionElement(gen, -my_factor[0]) 

 

# rnfequation needs a monic polynomial with integral coefficients. 

# We achieve this with a change of variables. 

 

den, my_factor = clear_denominators(my_factor) 

 

 

pari_nf = gen.pari_field() 

 

x, y = QQxy.gens() 

my_factor = QQxy['z']([c.polynomial()(y) for c in my_factor])(x) 

 

# XXX much duplicate code with AlgebraicGenerator.union() 

 

# XXX need more caching here 

newpol, self_pol, k = pari_nf.rnfequation(my_factor, 1) 

k = int(k) 

 

newpol_sage = QQx(newpol) 

newpol_sage_y = QQy(newpol_sage) 

 

red_elt, red_back, red_pol = do_polred(newpol_sage_y) 

 

new_nf = NumberField(red_pol, name='a', check=False) 

 

self_pol_sage = QQx(self_pol.lift()) 

 

new_nf_a = new_nf.gen() 

 

def intv_fn(prec): 

return conjugate_expand(red_elt(gen._interval_fast(prec) * k + self._interval_fast(prec) * den)) 

new_intv = conjugate_shrink(isolating_interval(intv_fn, red_pol)) 

 

root = ANRoot(QQx(red_pol), new_intv) 

new_gen = AlgebraicGenerator(new_nf, root) 

red_back_a = red_back(new_nf.gen()) 

new_poly = ((QQx_x - k * self_pol_sage)(red_back_a)/den) 

return ANExtensionElement(new_gen, new_poly) 

 

def _more_precision(self): 

""" 

Recompute the interval enclosing this ``ANRoot`` object at higher 

precision. 

 

EXAMPLES:: 

 

sage: x = polygen(QQ); y = (x^3 + x + 1).roots(AA,multiplicities=False)[0] 

sage: z = y._descr 

sage: z._interval.prec() 

64 

sage: z._more_precision() 

sage: z._interval.prec() 

128 

""" 

prec = self._interval.prec() 

self._interval = self.refine_interval(self._interval, prec*2) 

 

def _interval_fast(self, prec): 

""" 

Given a RealIntervalField, compute the value of this number 

using interval arithmetic of at least the precision of the field, 

and return the value in that field. (More precision may be used 

in the computation.) 

 

EXAMPLES:: 

 

sage: x = polygen(QQ); y = (x^3 + x + 1).roots(AA,multiplicities=False)[0]._descr 

sage: y._interval_fast(128) 

-0.68232780382801932736948373971104825689? 

 

Check that :trac:`15493` is fixed:: 

 

sage: y._interval_fast(20).parent() is RealIntervalField(20) 

True 

""" 

if prec == self._interval.prec(): 

return self._interval 

if prec < self._interval.prec(): 

return self._interval.parent().to_prec(prec)(self._interval) 

self._more_precision() 

return self._interval_fast(prec) 

 

class ANExtensionElement(ANDescr): 

r""" 

The subclass of ``ANDescr`` that represents a number field 

element in terms of a specific generator. Consists of a polynomial 

with rational coefficients in terms of the generator, and the 

generator itself, an ``AlgebraicGenerator``. 

""" 

 

def __new__(self, generator, value): 

if value.is_rational(): 

return ANRational(value._rational_()) 

else: 

return ANDescr.__new__(self) 

 

def __init__(self, generator, value): 

self._generator = generator 

self._value = value 

self._exactly_real = not generator.is_complex() 

 

def __reduce__(self): 

""" 

Add customized pickling support. 

 

EXAMPLES:: 

 

sage: x = polygen(QQ) 

sage: v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1] 

sage: v.exactify() 

sage: type(v._descr) 

<class 'sage.rings.qqbar.ANExtensionElement'> 

sage: loads(dumps(v)) == v 

True 

""" 

return (ANExtensionElement, (self._generator, self._value)) 

 

def _repr_(self): 

fgen = self._generator._field.gen() 

sgen = str(fgen) 

return '%s where %s = 0 and %s in %s'%(self._value, 

self._generator.field().polynomial()._repr(name=sgen), 

sgen, 

self._generator._interval_fast(53)) 

 

def handle_sage_input(self, sib, coerce, is_qqbar): 

r""" 

Produce an expression which will reproduce this value when evaluated, 

and an indication of whether this value is worth sharing (always True, 

for ``ANExtensionElement``). 

 

EXAMPLES:: 

 

sage: I = QQbar(I) 

sage: sage_input(3+4*I, verify=True) 

# Verified 

QQbar(3 + 4*I) 

sage: v = QQbar.zeta(3) + QQbar.zeta(5) 

sage: v - v == 0 

True 

sage: sage_input(vector(QQbar, (4-3*I, QQbar.zeta(7))), verify=True) 

# Verified 

R.<x> = AA[] 

vector(QQbar, [4 - 3*I, QQbar.polynomial_root(AA.common_polynomial(x^6 + x^5 + x^4 + x^3 + x^2 + x + 1), CIF(RIF(RR(0.62348980185873348), RR(0.62348980185873359)), RIF(RR(0.7818314824680298), RR(0.78183148246802991))))]) 

sage: sage_input(v, verify=True) 

# Verified 

R.<x> = AA[] 

v = QQbar.polynomial_root(AA.common_polynomial(x^8 - x^7 + x^5 - x^4 + x^3 - x + 1), CIF(RIF(RR(0.91354545764260087), RR(0.91354545764260098)), RIF(RR(0.40673664307580015), RR(0.40673664307580021)))) 

v^5 + v^3 

sage: v = QQbar(sqrt(AA(2))) 

sage: v.exactify() 

sage: sage_input(v, verify=True) 

# Verified 

R.<x> = AA[] 

QQbar(AA.polynomial_root(AA.common_polynomial(x^2 - 2), RIF(RR(1.4142135623730949), RR(1.4142135623730951)))) 

sage: from sage.rings.qqbar import * 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: extel = ANExtensionElement(QQbar_I_generator, QQbar_I_generator.field().gen() + 1) 

sage: extel.handle_sage_input(sib, False, True) 

({call: {atomic:QQbar}({binop:+ {atomic:1} {atomic:I}})}, True) 

""" 

if self._generator is QQbar_I_generator: 

assert(is_qqbar) 

re, im = self._value.list() 

im_part = sib.prod([sib(im, True), sib.name('I')], simplify=True) 

v = sib.sum([sib(re, True), im_part], simplify=True) 

if coerce != 2: 

v = sib.name('QQbar')(v) 

return (v, True) 

return (v, False) 

 

result_is_qqbar = self._generator.is_complex() 

 

rt = sib(self._generator.root_as_algebraic()) 

# For the best fidelity, we really ought to somehow ensure 

# that rt is exactified, but sage_input doesn't support that 

# nicely. Skip it for now. 

# The following is copied with slight mods from polynomial_element.pyx 

coeffs = [sib(c, True) for c in self._value.list()] 

terms = [] 

for i in range(len(coeffs)-1, -1, -1): 

if i > 0: 

if i > 1: 

rt_pow = rt**sib.int(i) 

else: 

rt_pow = rt 

terms.append(sib.prod((coeffs[i], rt_pow), simplify=True)) 

else: 

terms.append(coeffs[i]) 

v = sib.sum(terms, simplify=True) 

if result_is_qqbar != is_qqbar: 

v = sib.name('QQbar' if is_qqbar else 'AA')(v) 

return (v, True) 

 

def is_complex(self): 

r""" 

Return True if the number field that defines this element is not real. 

This does not imply that the element itself is definitely non-real, as 

in the example below. 

 

EXAMPLES:: 

 

sage: rt2 = QQbar(sqrt(2)) 

sage: rtm3 = QQbar(sqrt(-3)) 

sage: x = rtm3 + rt2 - rtm3 

sage: x.exactify() 

sage: y = x._descr 

sage: type(y) 

<class 'sage.rings.qqbar.ANExtensionElement'> 

sage: y.is_complex() 

True 

sage: x.imag() == 0 

True 

""" 

return not self._exactly_real 

 

def is_simple(self): 

r""" 

Checks whether this descriptor represents a value with the same 

algebraic degree as the number field associated with the descriptor. 

 

For ``ANExtensionElement`` elements, we check this by 

comparing the degree of the minimal polynomial to the degree 

of the field. 

 

EXAMPLES:: 

 

sage: rt2 = AA(sqrt(2)) 

sage: rt3 = AA(sqrt(3)) 

sage: rt2b = rt3 + rt2 - rt3 

sage: rt2.exactify() 

sage: rt2._descr 

a where a^2 - 2 = 0 and a in 1.414213562373095? 

sage: rt2._descr.is_simple() 

True 

 

sage: rt2b.exactify() 

sage: rt2b._descr 

a^3 - 3*a where a^4 - 4*a^2 + 1 = 0 and a in 1.931851652578137? 

sage: rt2b._descr.is_simple() 

False 

""" 

try: 

return self._is_simple 

except AttributeError: 

self._is_simple = (self.minpoly().degree() == self.generator().field().degree()) 

return self._is_simple 

 

def generator(self): 

r""" 

Return the :class:`~AlgebraicGenerator` object corresponding to self. 

 

EXAMPLES:: 

 

sage: v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.exactify() 

sage: v.generator() 

Number Field in a with defining polynomial y^2 - y - 1 with a in 1.618033988749895? 

""" 

return self._generator 

 

def exactify(self): 

r""" 

Return an exact representation of self. Since self is already exact, 

just return self. 

 

EXAMPLES:: 

 

sage: v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.exactify() 

sage: type(v) 

<class 'sage.rings.qqbar.ANExtensionElement'> 

sage: v.exactify() is v 

True 

""" 

return self 

 

def field_element_value(self): 

r""" 

Return the underlying number field element. 

 

EXAMPLES:: 

 

sage: v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.exactify() 

sage: v.field_element_value() 

a 

""" 

return self._value 

 

def minpoly(self): 

""" 

Compute the minimal polynomial of this algebraic number. 

 

EXAMPLES:: 

 

sage: v = (x^2 - x - 1).roots(ring=AA, multiplicities=False)[1]._descr.exactify() 

sage: type(v) 

<class 'sage.rings.qqbar.ANExtensionElement'> 

sage: v.minpoly() 

x^2 - x - 1 

""" 

try: 

return self._minpoly 

except AttributeError: 

self._minpoly = self._value.minpoly() 

return self._minpoly 

 

def simplify(self, n): 

""" 

Compute an exact representation for this descriptor, in the 

smallest possible number field. 

 

INPUT: 

 

- ``n`` -- The element of ``AA`` or ``QQbar`` corresponding 

to this descriptor. 

 

EXAMPLES:: 

 

sage: rt2 = AA(sqrt(2)) 

sage: rt3 = AA(sqrt(3)) 

sage: rt2b = rt3 + rt2 - rt3 

sage: rt2b.exactify() 

sage: rt2b._descr 

a^3 - 3*a where a^4 - 4*a^2 + 1 = 0 and a in 1.931851652578137? 

sage: rt2b._descr.simplify(rt2b) 

a where a^2 - 2 = 0 and a in 1.414213562373095? 

""" 

 

if self.is_simple(): 

return self 

 

# This is very inefficient... 

# for instance, the .exactify() call will try to factor poly, 

# even though we know that poly is irreducible 

poly = self.minpoly() 

intv = isolating_interval(lambda prec: n._interval_fast(prec), poly) 

new_v = QQbar.polynomial_root(poly, intv) 

new_v.exactify() 

return new_v._descr 

 

def _interval_fast(self, prec): 

gen_val = self._generator._interval_fast(prec) 

v = self._value.polynomial()(gen_val) 

if self._exactly_real and is_ComplexIntervalFieldElement(v): 

return v.real() 

return v 

 

# for these three functions the argument n is not used (but it is there 

# anyway for compatibility) 

 

def neg(self, n): 

r""" 

Negation of self. 

 

EXAMPLES:: 

 

sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(-3)) 

sage: a.exactify() 

sage: b = a._descr 

sage: type(b) 

<class 'sage.rings.qqbar.ANExtensionElement'> 

sage: b.neg(a) 

1/3*a^3 - 2/3*a^2 + 4/3*a - 2 where a^4 - 2*a^3 + a^2 - 6*a + 9 = 0 and a in -0.7247448713915890? - 1.573132184970987?*I 

sage: b.neg("ham spam and eggs") 

1/3*a^3 - 2/3*a^2 + 4/3*a - 2 where a^4 - 2*a^3 + a^2 - 6*a + 9 = 0 and a in -0.7247448713915890? - 1.573132184970987?*I 

""" 

return ANExtensionElement(self._generator, -self._value) 

 

def invert(self, n): 

r""" 

1/self. 

 

EXAMPLES:: 

 

sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(-3)) 

sage: a.exactify() 

sage: b = a._descr 

sage: type(b) 

<class 'sage.rings.qqbar.ANExtensionElement'> 

sage: b.invert(a) 

7/3*a^3 - 2/3*a^2 + 4/3*a - 12 where a^4 - 2*a^3 + a^2 - 6*a + 9 = 0 and a in -0.7247448713915890? - 1.573132184970987?*I 

sage: b.invert("ham spam and eggs") 

7/3*a^3 - 2/3*a^2 + 4/3*a - 12 where a^4 - 2*a^3 + a^2 - 6*a + 9 = 0 and a in -0.7247448713915890? - 1.573132184970987?*I 

""" 

return ANExtensionElement(self._generator, ~self._value) 

 

def conjugate(self, n): 

r""" 

Negation of self. 

 

EXAMPLES:: 

 

sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(-3)) 

sage: a.exactify() 

sage: b = a._descr 

sage: type(b) 

<class 'sage.rings.qqbar.ANExtensionElement'> 

sage: b.conjugate(a) 

-1/3*a^3 + 2/3*a^2 - 4/3*a + 2 where a^4 - 2*a^3 + a^2 - 6*a + 9 = 0 and a in -0.7247448713915890? + 1.573132184970987?*I 

sage: b.conjugate("ham spam and eggs") 

-1/3*a^3 + 2/3*a^2 - 4/3*a + 2 where a^4 - 2*a^3 + a^2 - 6*a + 9 = 0 and a in -0.7247448713915890? + 1.573132184970987?*I 

""" 

if self._exactly_real: 

return self 

else: 

return ANExtensionElement(self._generator.conjugate(), self._value) 

 

# The rest of these unary operations do actually use n, which is an 

# AlgebraicNumber pointing to self. 

 

def norm(self, n): 

r""" 

Norm of self (square of complex absolute value) 

 

EXAMPLES:: 

 

sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(-3)) 

sage: a.exactify() 

sage: b = a._descr 

sage: type(b) 

<class 'sage.rings.qqbar.ANExtensionElement'> 

sage: b.norm(a) 

<sage.rings.qqbar.ANUnaryExpr object at ...> 

""" 

if self._exactly_real: 

return (n*n)._descr 

elif self._generator is QQbar_I_generator: 

return ANRational(self._value.norm()) 

else: 

return ANUnaryExpr(n, 'norm') 

 

def abs(self, n): 

r""" 

Return the absolute value of self (square root of the norm). 

 

EXAMPLES:: 

 

sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(-3)) 

sage: a.exactify() 

sage: b = a._descr 

sage: type(b) 

<class 'sage.rings.qqbar.ANExtensionElement'> 

sage: b.abs(a) 

Root 3.146264369941972342? of x^2 - 9.89897948556636? 

""" 

return AlgebraicReal(self.norm(n)).sqrt()._descr 

 

def rational_argument(self, n): 

r""" 

If the argument of self is `2\pi` times some rational number in `[1/2, 

-1/2)`, return that rational; otherwise, return ``None``. 

 

EXAMPLES:: 

 

sage: a = QQbar(sqrt(-2)) + QQbar(sqrt(3)) 

sage: a.exactify() 

sage: b = a._descr 

sage: type(b) 

<class 'sage.rings.qqbar.ANExtensionElement'> 

sage: b.rational_argument(a) is None 

True 

sage: x = polygen(QQ) 

sage: a = (x^4 + 1).roots(QQbar, multiplicities=False)[0] 

sage: a.exactify() 

sage: b = a._descr 

sage: b.rational_argument(a) 

-3/8 

""" 

# If the argument of self is 2*pi times some rational number a/b, 

# then self/abs(self) is a root of the b'th cyclotomic polynomial. 

# This implies that the algebraic degree of self is at least 

# phi(b). Working backward, we know that the algebraic degree 

# of self is at most the degree of the generator, so that gives 

# an upper bound on phi(b). According to 

# http://mathworld.wolfram.com/TotientFunction.html, 

# phi(b) >= sqrt(b) for b > 6; this gives us an upper bound on b. 

# We then check to see if this is possible; if so, we test 

# to see if it actually holds. 

 

if self._exactly_real: 

if n > 0: 

return QQ.zero() 

else: 

return QQ((1,2)) 

 

gen_degree = self._generator._field.degree() 

if gen_degree <= 2: 

max_b = 6 

else: 

max_b = gen_degree*gen_degree 

rat_arg_fl = n._interval_fast(128).argument() / RealIntervalField(128).pi() / 2 

rat_arg = rat_arg_fl.simplest_rational() 

if rat_arg.denominator() > max_b: 

return None 

n_exp = n ** rat_arg.denominator() 

if n_exp.real() > AA.zero() and n_exp.imag().is_zero(): 

return rat_arg 

# Strictly speaking, we need to look for the second-simplest 

# rational in rat_arg_fl and make sure its denominator is > max_b. 

# For now, we just punt. 

raise NotImplementedError 

 

class ANUnaryExpr(ANDescr): 

def __init__(self, arg, op): 

r""" 

Initialize this ANUnaryExpr. 

 

EXAMPLES:: 

 

sage: t = ~QQbar(sqrt(2)); type(t._descr) # indirect doctest 

<class 'sage.rings.qqbar.ANUnaryExpr'> 

""" 

self._arg = arg 

self._op = op 

self._complex = True 

 

def __reduce__(self): 

""" 

Add customized pickling support. 

 

EXAMPLES:: 

 

sage: t = ~QQbar(sqrt(2)); type(t._descr) 

<class 'sage.rings.qqbar.ANUnaryExpr'> 

sage: loads(dumps(t)) == 1/QQbar(sqrt(2)) 

True 

""" 

return (ANUnaryExpr, (self._arg, self._op)) 

 

def handle_sage_input(self, sib, coerce, is_qqbar): 

r""" 

Produce an expression which will reproduce this value when evaluated, 

and an indication of whether this value is worth sharing (always 

True for ``ANUnaryExpr``). 

 

EXAMPLES:: 

 

sage: sage_input(-sqrt(AA(2)), verify=True) 

# Verified 

R.<x> = AA[] 

-AA.polynomial_root(AA.common_polynomial(x^2 - 2), RIF(RR(1.4142135623730949), RR(1.4142135623730951))) 

sage: sage_input(~sqrt(AA(2)), verify=True) 

# Verified 

R.<x> = AA[] 

~AA.polynomial_root(AA.common_polynomial(x^2 - 2), RIF(RR(1.4142135623730949), RR(1.4142135623730951))) 

sage: sage_input(sqrt(QQbar(-3)).conjugate(), verify=True) 

# Verified 

R.<x> = QQbar[] 

QQbar.polynomial_root(AA.common_polynomial(x^2 + 3), CIF(RIF(RR(0)), RIF(RR(1.7320508075688772), RR(1.7320508075688774)))).conjugate() 

sage: sage_input(QQbar.zeta(3).real(), verify=True) 

# Verified 

R.<x> = AA[] 

QQbar.polynomial_root(AA.common_polynomial(x^2 + x + 1), CIF(RIF(-RR(0.50000000000000011), -RR(0.49999999999999994)), RIF(RR(0.8660254037844386), RR(0.86602540378443871)))).real() 

sage: sage_input(QQbar.zeta(3).imag(), verify=True) 

# Verified 

R.<x> = AA[] 

QQbar.polynomial_root(AA.common_polynomial(x^2 + x + 1), CIF(RIF(-RR(0.50000000000000011), -RR(0.49999999999999994)), RIF(RR(0.8660254037844386), RR(0.86602540378443871)))).imag() 

sage: sage_input(abs(sqrt(QQbar(-3))), verify=True) 

# Verified 

R.<x> = QQbar[] 

abs(QQbar.polynomial_root(AA.common_polynomial(x^2 + 3), CIF(RIF(RR(0)), RIF(RR(1.7320508075688772), RR(1.7320508075688774))))) 

sage: sage_input(sqrt(QQbar(-3)).norm(), verify=True) 

# Verified 

R.<x> = QQbar[] 

QQbar.polynomial_root(AA.common_polynomial(x^2 + 3), CIF(RIF(RR(0)), RIF(RR(1.7320508075688772), RR(1.7320508075688774)))).norm() 

sage: sage_input(QQbar(QQbar.zeta(3).real()), verify=True) 

# Verified 

R.<x> = AA[] 

QQbar(QQbar.polynomial_root(AA.common_polynomial(x^2 + x + 1), CIF(RIF(-RR(0.50000000000000011), -RR(0.49999999999999994)), RIF(RR(0.8660254037844386), RR(0.86602540378443871)))).real()) 

sage: from sage.rings.qqbar import * 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: unexp = ANUnaryExpr(sqrt(AA(2)), '~') 

sage: unexp.handle_sage_input(sib, False, False) 

({unop:~ {call: {getattr: {atomic:AA}.polynomial_root}({call: {getattr: {atomic:AA}.common_polynomial}({binop:- {binop:** {gen:x {constr_parent: {subscr: {atomic:AA}[{atomic:'x'}]} with gens: ('x',)}} {atomic:2}} {atomic:2}})}, {call: {atomic:RIF}({call: {atomic:RR}({atomic:1.4142135623730949})}, {call: {atomic:RR}({atomic:1.4142135623730951})})})}}, 

True) 

sage: unexp.handle_sage_input(sib, False, True) 

({call: {atomic:QQbar}({unop:~ {call: {getattr: {atomic:AA}.polynomial_root}({call: {getattr: {atomic:AA}.common_polynomial}({binop:- {binop:** {gen:x {constr_parent: {subscr: {atomic:AA}[{atomic:'x'}]} with gens: ('x',)}} {atomic:2}} {atomic:2}})}, {call: {atomic:RIF}({call: {atomic:RR}({atomic:1.4142135623730949})}, {call: {atomic:RR}({atomic:1.4142135623730951})})})}})}, 

True) 

""" 

arg_is_qqbar = self._arg.parent() is QQbar 

v = sib(self._arg) 

op = self._op 

if op == '-': 

v = -v 

elif op == '~': 

v = ~v 

elif op == 'conjugate': 

v = v.conjugate() 

elif op == 'real': 

v = v.real() 

elif op == 'imag': 

v = v.imag() 

elif op == 'abs': 

v = abs(v) 

elif op == 'norm': 

v = v.norm() 

else: 

raise NotImplementedError 

 

result_is_qqbar = arg_is_qqbar 

if op in ('real', 'imag', 'abs', 'norm'): 

result_is_qqbar = False 

if result_is_qqbar != is_qqbar: 

# The following version is not safe with respect to caching; 

# with the current sage_input.py, anything that gets entered 

# into the cache must be safe at all coercion levels. 

# if is_qqbar and not coerce: 

# v = sib.name('QQbar')(v) 

# if not is_qqbar and coerce != 2: 

# v = sib.name('AA')(v) 

v = sib.name('QQbar' if is_qqbar else 'AA')(v) 

 

return (v, True) 

 

def is_complex(self): 

r""" 

Return whether or not this element is complex. Note that this is a data 

type check, and triggers no computations -- if it returns False, the 

element might still be real, it just doesn't know it yet. 

 

EXAMPLES:: 

 

sage: t = AA(sqrt(2)) 

sage: s = (-t)._descr 

sage: s 

<sage.rings.qqbar.ANUnaryExpr object at ...> 

sage: s.is_complex() 

False 

sage: QQbar(-sqrt(2))._descr.is_complex() 

True 

""" 

return self._complex 

 

def _interval_fast(self, prec): 

r""" 

Calculate an approximation to this ``ANUnaryExpr`` object in an interval field of precision ``prec``. 

 

EXAMPLES:: 

 

sage: t = AA(sqrt(2)) 

sage: s = (-t)._descr 

sage: s 

<sage.rings.qqbar.ANUnaryExpr object at ...> 

sage: s._interval_fast(150) 

-1.414213562373095048801688724209698078569671876? 

""" 

op = self._op 

 

v = self._arg._interval_fast(prec) 

 

if not is_ComplexIntervalFieldElement(v): 

self._complex = False 

 

if op == '-': 

return -v 

 

if op == '~': 

return ~v 

 

if op == 'conjugate': 

if is_ComplexIntervalFieldElement(v): 

return v.conjugate() 

else: 

return v 

 

self._complex = False 

 

if op == 'real': 

if is_ComplexIntervalFieldElement(v): 

return v.real() 

else: 

return v 

 

if op == 'imag': 

if is_ComplexIntervalFieldElement(v): 

return v.imag() 

else: 

return RealIntervalField(prec)(0) 

 

if op == 'abs': 

return abs(v) 

 

if op == 'norm': 

if is_ComplexIntervalFieldElement(v): 

return v.norm() 

else: 

return v.square() 

 

raise NotImplementedError 

 

def exactify(self): 

r""" 

Trigger exact computation of self. 

 

EXAMPLES:: 

 

sage: v = (-QQbar(sqrt(2)))._descr 

sage: type(v) 

<class 'sage.rings.qqbar.ANUnaryExpr'> 

sage: v.exactify() 

-a where a^2 - 2 = 0 and a in 1.414213562373095? 

""" 

op = self._op 

arg = self._arg 

 

if op == '-': 

arg.exactify() 

return arg._descr.neg(None) 

 

if op == '~': 

arg.exactify() 

return arg._descr.invert(None) 

 

if op == 'real': 

arg.exactify() 

rv = (arg + arg.conjugate()) / 2 

rv.exactify() 

rvd = rv._descr 

rvd._exactly_real = True 

return rvd 

 

if op == 'imag': 

arg.exactify() 

iv = QQbar_I * (arg.conjugate() - arg) / 2 

iv.exactify() 

ivd = iv._descr 

ivd._exactly_real = True 

return ivd 

 

if op == 'abs': 

arg.exactify() 

if arg.parent() is AA: 

if arg.sign() > 0: 

return arg._descr 

else: 

return arg._descr.neg(None) 

 

v = (arg * arg.conjugate()).sqrt() 

v.exactify() 

vd = v._descr 

vd._exactly_real = True 

return vd 

 

if op == 'norm': 

arg.exactify() 

v = arg * arg.conjugate() 

v.exactify() 

vd = v._descr 

vd._exactly_real = True 

return vd 

 

if op == 'conjugate': 

arg.exactify() 

return arg._descr.conjugate(None) 

 

class ANBinaryExpr(ANDescr): 

def __init__(self, left, right, op): 

r""" 

Initialize this ANBinaryExpr. 

 

EXAMPLES:: 

 

sage: t = QQbar(sqrt(2)) + QQbar(sqrt(3)); type(t._descr) # indirect doctest 

<class 'sage.rings.qqbar.ANBinaryExpr'> 

""" 

self._left = left 

self._right = right 

self._op = op 

self._complex = True 

 

def __reduce__(self): 

""" 

Add customized pickling support. 

 

EXAMPLES:: 

 

sage: t = QQbar(sqrt(2)) + QQbar(sqrt(3)); type(t._descr) 

<class 'sage.rings.qqbar.ANBinaryExpr'> 

sage: loads(dumps(t)) == QQbar(sqrt(2)) + QQbar(sqrt(3)) 

True 

""" 

return (ANBinaryExpr, (self._left, self._right, self._op)) 

 

def handle_sage_input(self, sib, coerce, is_qqbar): 

r""" 

Produce an expression which will reproduce this value when evaluated, 

and an indication of whether this value is worth sharing (always 

True for ``ANBinaryExpr``). 

 

EXAMPLES:: 

 

sage: sage_input(2 + sqrt(AA(2)), verify=True) 

# Verified 

R.<x> = AA[] 

2 + AA.polynomial_root(AA.common_polynomial(x^2 - 2), RIF(RR(1.4142135623730949), RR(1.4142135623730951))) 

sage: sage_input(sqrt(AA(2)) + 2, verify=True) 

# Verified 

R.<x> = AA[] 

AA.polynomial_root(AA.common_polynomial(x^2 - 2), RIF(RR(1.4142135623730949), RR(1.4142135623730951))) + 2 

sage: sage_input(2 - sqrt(AA(2)), verify=True) 

# Verified 

R.<x> = AA[] 

2 - AA.polynomial_root(AA.common_polynomial(x^2 - 2), RIF(RR(1.4142135623730949), RR(1.4142135623730951))) 

sage: sage_input(2 / sqrt(AA(2)), verify=True) 

# Verified 

R.<x> = AA[] 

2/AA.polynomial_root(AA.common_polynomial(x^2 - 2), RIF(RR(1.4142135623730949), RR(1.4142135623730951))) 

sage: sage_input(2 + (-1*sqrt(AA(2))), verify=True) 

# Verified 

R.<x> = AA[] 

2 - AA.polynomial_root(AA.common_polynomial(x^2 - 2), RIF(RR(1.4142135623730949), RR(1.4142135623730951))) 

sage: sage_input(2*sqrt(AA(2)), verify=True) 

# Verified 

R.<x> = AA[] 

2*AA.polynomial_root(AA.common_polynomial(x^2 - 2), RIF(RR(1.4142135623730949), RR(1.4142135623730951))) 

sage: rt2 = sqrt(AA(2)) 

sage: one = rt2/rt2 

sage: n = one+3 

sage: sage_input(n) 

R.<x> = AA[] 

v = AA.polynomial_root(AA.common_polynomial(x^2 - 2), RIF(RR(1.4142135623730949), RR(1.4142135623730951))) 

v/v + 3 

sage: one == 1 

True 

sage: sage_input(n) 

1 + AA(3) 

sage: rt3 = QQbar(sqrt(3)) 

sage: one = rt3/rt3 

sage: n = sqrt(AA(2))+one 

sage: one == 1 

True 

sage: sage_input(n) 

R.<x> = AA[] 

QQbar.polynomial_root(AA.common_polynomial(x^2 - 2), RIF(RR(1.4142135623730949), RR(1.4142135623730951))) + 1 

sage: from sage.rings.qqbar import * 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: sib = SageInputBuilder() 

sage: binexp = ANBinaryExpr(AA(3), AA(5), operator.mul) 

sage: binexp.handle_sage_input(sib, False, False) 

({binop:* {atomic:3} {call: {atomic:AA}({atomic:5})}}, True) 

sage: binexp.handle_sage_input(sib, False, True) 

({call: {atomic:QQbar}({binop:* {atomic:3} {call: {atomic:AA}({atomic:5})}})}, True) 

""" 

arg1 = self._left 

arg2 = self._right 

op = self._op 

 

# We want 2+QQbar.zeta(3) and QQbar.zeta(3)+2, not 

# QQbar(2)+QQbar.zeta(3). So we want to pass coerced=True to 

# an argument if it is rational (but if both arguments are 

# rational, we only want to set it for one of them). 

 

arg1_coerced = False 

arg2_coerced = False 

 

if isinstance(arg1._descr, ANRational): 

arg1_coerced = True 

elif isinstance(arg2._descr, ANRational): 

arg2_coerced = True 

 

arg1_is_qqbar = arg1.parent() is QQbar 

arg2_is_qqbar = arg2.parent() is QQbar 

 

result_is_qqbar = \ 

(arg1_is_qqbar and not arg1_coerced) or \ 

(arg2_is_qqbar and not arg2_coerced) 

 

v1 = sib(arg1, arg1_coerced) 

v2 = sib(arg2, arg2_coerced) 

 

if op is operator.add: 

v = sib.sum([v1, v2], simplify=True) 

elif op is operator.sub: 

v = sib.sum([v1, -v2], simplify=True) 

elif op is operator.mul: 

v = sib.prod([v1, v2], simplify=True) 

elif op is operator.truediv: 

v = v1 / v2 

else: 

raise RuntimeError("op is {}".format(op)) 

 

if result_is_qqbar != is_qqbar: 

# The following version is not safe with respect to caching; 

# with the current sage_input.py, anything that gets entered 

# into the cache must be safe at all coercion levels. 

# if is_qqbar and not coerce: 

# v = sib.name('QQbar')(v) 

# if not is_qqbar and coerce != 2: 

# v = sib.name('AA')(v) 

v = sib.name('QQbar' if is_qqbar else 'AA')(v) 

 

return (v, True) 

 

def is_complex(self): 

r""" 

Whether this element is complex. Does not trigger exact computation, so 

may return True even if the element is real. 

 

EXAMPLES:: 

 

sage: x = (QQbar(sqrt(-2)) / QQbar(sqrt(-5)))._descr 

sage: x.is_complex() 

True 

""" 

return self._complex 

 

def _interval_fast(self, prec): 

r""" 

Calculate an approximation to self in an interval field of precision prec. 

 

EXAMPLES:: 

 

sage: x = (QQbar(sqrt(-2)) / QQbar(sqrt(-5)))._descr 

sage: y= x._interval_fast(64); y 

0.632455532033675867? 

sage: y.parent() 

Complex Interval Field with 64 bits of precision 

""" 

op = self._op 

 

lv = self._left._interval_fast(prec) 

rv = self._right._interval_fast(prec) 

 

if not (is_ComplexIntervalFieldElement(lv) or is_ComplexIntervalFieldElement(rv)): 

self._complex = False 

 

return op(lv, rv) 

 

def exactify(self): 

""" 

TESTS:: 

 

sage: rt2c = QQbar.zeta(3) + AA(sqrt(2)) - QQbar.zeta(3) 

sage: rt2c.exactify() 

 

We check to make sure that this method still works even. We 

do this by increasing the recursion level at each step and 

decrease it before we return:: 

 

sage: import sys; sys.getrecursionlimit() 

1000 

sage: s = SymmetricFunctions(QQ).schur() 

sage: a=s([3,2]).expand(8)(flatten([[QQbar.zeta(3)^d for d in range(3)], [QQbar.zeta(5)^d for d in range(5)]])) 

sage: a.exactify(); a # long time 

0 

sage: sys.getrecursionlimit() 

1000 

 

""" 

import sys 

old_recursion_limit = sys.getrecursionlimit() 

sys.setrecursionlimit(old_recursion_limit + 10) 

try: 

left = self._left 

right = self._right 

left.exactify() 

right.exactify() 

gen = left._exact_field().union(right._exact_field()) 

left_value = gen(left._exact_value()) 

right_value = gen(right._exact_value()) 

 

value = self._op(left_value, right_value) 

 

if gen.is_trivial(): 

return ANRational(value) 

else: 

return ANExtensionElement(gen, value) 

finally: 

sys.setrecursionlimit(old_recursion_limit) 

 

# These are the functions used to add, subtract, multiply, and divide 

# algebraic numbers. Basically, we try to compute exactly if both 

# arguments are already known to be in the same number field. Otherwise 

# we fall back to floating-point computation to be backed up by exact 

# symbolic computation only as required. 

 

def an_binop_rational(a, b, op): 

r""" 

Used to add, subtract, multiply or divide algebraic numbers. 

 

Used when both are actually rational. 

 

EXAMPLES:: 

 

sage: from sage.rings.qqbar import an_binop_rational 

sage: f = an_binop_rational(QQbar(2), QQbar(3/7), operator.add) 

sage: f 

17/7 

sage: type(f) 

<class 'sage.rings.qqbar.ANRational'> 

 

sage: f = an_binop_rational(QQbar(2), QQbar(3/7), operator.mul) 

sage: f 

6/7 

sage: type(f) 

<class 'sage.rings.qqbar.ANRational'> 

""" 

return ANRational(op(a._descr._value, b._descr._value)) 

 

def an_binop_expr(a, b, op): 

r""" 

Add, subtract, multiply or divide algebraic numbers represented as 

binary expressions. 

 

INPUT: 

 

- ``a``, ``b`` -- two elements 

 

- ``op`` -- an operator 

 

EXAMPLES:: 

 

sage: a = QQbar(sqrt(2)) + QQbar(sqrt(3)) 

sage: b = QQbar(sqrt(3)) + QQbar(sqrt(5)) 

sage: type(a._descr); type(b._descr) 

<class 'sage.rings.qqbar.ANBinaryExpr'> 

<class 'sage.rings.qqbar.ANBinaryExpr'> 

sage: from sage.rings.qqbar import an_binop_expr 

sage: x = an_binop_expr(a, b, operator.add); x 

<sage.rings.qqbar.ANBinaryExpr object at ...> 

sage: x.exactify() 

-6/7*a^7 + 2/7*a^6 + 71/7*a^5 - 26/7*a^4 - 125/7*a^3 + 72/7*a^2 + 43/7*a - 47/7 where a^8 - 12*a^6 + 23*a^4 - 12*a^2 + 1 = 0 and a in 3.12580...? 

 

sage: a = QQbar(sqrt(2)) + QQbar(sqrt(3)) 

sage: b = QQbar(sqrt(3)) + QQbar(sqrt(5)) 

sage: type(a._descr) 

<class 'sage.rings.qqbar.ANBinaryExpr'> 

sage: x = an_binop_expr(a, b, operator.mul); x 

<sage.rings.qqbar.ANBinaryExpr object at ...> 

sage: x.exactify() 

2*a^7 - a^6 - 24*a^5 + 12*a^4 + 46*a^3 - 22*a^2 - 22*a + 9 where a^8 - 12*a^6 + 23*a^4 - 12*a^2 + 1 = 0 and a in 3.1258...? 

""" 

return ANBinaryExpr(a, b, op) 

 

def an_binop_element(a, b, op): 

r""" 

Add, subtract, multiply or divide two elements represented as elements of 

number fields. 

 

EXAMPLES:: 

 

sage: sqrt2 = QQbar(2).sqrt() 

sage: sqrt3 = QQbar(3).sqrt() 

sage: sqrt5 = QQbar(5).sqrt() 

 

sage: a = sqrt2 + sqrt3; a.exactify() 

sage: b = sqrt3 + sqrt5; b.exactify() 

sage: type(a._descr) 

<class 'sage.rings.qqbar.ANExtensionElement'> 

sage: from sage.rings.qqbar import an_binop_element 

sage: an_binop_element(a, b, operator.add) 

<sage.rings.qqbar.ANBinaryExpr object at ...> 

sage: an_binop_element(a, b, operator.sub) 

<sage.rings.qqbar.ANBinaryExpr object at ...> 

sage: an_binop_element(a, b, operator.mul) 

<sage.rings.qqbar.ANBinaryExpr object at ...> 

sage: an_binop_element(a, b, operator.truediv) 

<sage.rings.qqbar.ANBinaryExpr object at ...> 

 

The code tries to use existing unions of number fields:: 

 

sage: sqrt17 = QQbar(17).sqrt() 

sage: sqrt19 = QQbar(19).sqrt() 

sage: a = sqrt17 + sqrt19 

sage: b = sqrt17 * sqrt19 - sqrt17 + sqrt19 * (sqrt17 + 2) 

sage: b, type(b._descr) 

(40.53909377268655?, <class 'sage.rings.qqbar.ANBinaryExpr'>) 

sage: a.exactify() 

sage: b = sqrt17 * sqrt19 - sqrt17 + sqrt19 * (sqrt17 + 2) 

sage: b, type(b._descr) 

(40.53909377268655?, <class 'sage.rings.qqbar.ANExtensionElement'>) 

""" 

ad = a._descr 

bd = b._descr 

adg = ad.generator() 

bdg = bd.generator() 

if adg == qq_generator or adg == bdg: 

return ANExtensionElement(bdg, op(ad._value, bd._value)) 

 

if bdg == qq_generator: 

return ANExtensionElement(adg, op(ad._value, bd._value)) 

 

if adg in bdg._unions or bdg in adg._unions: 

p = bdg._unions[adg] if adg in bdg._unions else adg._unions[bdg] 

p = p.parent 

adg2 = adg.super_poly(p) 

bdg2 = bdg.super_poly(p) 

av = ad._value.polynomial()(adg2) 

bv = bd._value.polynomial()(bdg2) 

v = op(av, bv) 

return ANExtensionElement(p, op(av, bv)) 

 

adg2 = adg.super_poly(bdg) 

if adg2 is not None: 

av = ad._value.polynomial()(adg2) 

return ANExtensionElement(bdg, op(av, bd._value)) 

 

bdg2 = bdg.super_poly(adg) 

if bdg2 is not None: 

bv = bd._value.polynomial()(bdg2) 

return ANExtensionElement(adg, op(ad._value, bv)) 

 

return ANBinaryExpr(a, b, op) 

 

# instanciation of the multimethod dispatch 

_binop_algo[ANRational, ANRational] = an_binop_rational 

_binop_algo[ANRational, ANExtensionElement] = \ 

_binop_algo[ANExtensionElement, ANRational] = \ 

_binop_algo[ANExtensionElement, ANExtensionElement ] = an_binop_element 

for t1 in (ANRational, ANRoot, ANExtensionElement, ANUnaryExpr, ANBinaryExpr): 

for t2 in (ANUnaryExpr, ANBinaryExpr, ANRoot): 

_binop_algo[t1, t2] = _binop_algo[t2, t1] = an_binop_expr 

 

qq_generator = AlgebraicGenerator(QQ, ANRoot(AAPoly.gen() - 1, RIF(1))) 

 

 

def _init_qqbar(): 

""" 

This code indirectly uses a huge amount of sage, despite the fact 

that qqbar is imported rather early on in the sage loading. This function 

is called at the end of sage.all. 

 

EXAMPLES:: 

 

sage: sage.rings.qqbar.QQbar_I_generator # indirect doctest 

Number Field in I with defining polynomial x^2 + 1 with a in 1*I 

""" 

global ZZX_x, AA_0, QQbar_I, AA_hash_offset, QQbar_hash_offset, QQbar_I_generator, QQbar_I_nf 

global QQ_0, QQ_1, QQ_1_2, QQ_1_4, RR_1_10 

 

RR_1_10 = RR(1)/10 

QQ_0 = QQ.zero() 

QQ_1 = QQ.one() 

QQ_1_2 = QQ((1,2)) 

QQ_1_4 = QQ((1,4)) 

 

AA_0 = AA.zero() 

 

QQbar_I_nf = QuadraticField(-1, 'I', embedding=CC.gen(), latex_name='i') 

QQbar_I_generator = AlgebraicGenerator(QQbar_I_nf, ANRoot(AAPoly.gen()**2 + 1, CIF(0, 1))) 

QQbar_I = AlgebraicNumber(ANExtensionElement(QQbar_I_generator, QQbar_I_nf.gen())) 

 

AA_hash_offset = AA(~ZZ(123456789)) 

 

QQbar_hash_offset = AlgebraicNumber(ANExtensionElement(QQbar_I_generator, ~ZZ(123456789) + QQbar_I_nf.gen()/ZZ(987654321))) 

 

ZZX_x = ZZ['x'].gen() 

 

# This is used in the _algebraic_ method of the golden_ratio constant, 

# in sage/symbolic/constants.py 

AA_golden_ratio = None 

 

def get_AA_golden_ratio(): 

r""" 

Return the golden ratio as an element of the algebraic real field. Used by 

:meth:`sage.symbolic.constants.golden_ratio._algebraic_`. 

 

EXAMPLES:: 

 

sage: AA(golden_ratio) # indirect doctest 

1.618033988749895? 

""" 

global AA_golden_ratio 

if AA_golden_ratio is None: 

AA_golden_ratio_nf = NumberField(ZZX_x**2 - ZZX_x - 1, 'phi') 

AA_golden_ratio_generator = AlgebraicGenerator(AA_golden_ratio_nf, ANRoot(AAPoly.gen()**2 - AAPoly.gen() - 1, RIF(1.618, 1.6181))) 

AA_golden_ratio = AlgebraicReal(ANExtensionElement(AA_golden_ratio_generator, AA_golden_ratio_nf.gen())) 

return AA_golden_ratio 

 

class ANRootOfUnity(ANExtensionElement): 

r""" 

Deprecated class to support unpickling 

 

TESTS:: 

 

sage: from sage.rings.qqbar import ANRootOfUnity 

sage: ANRootOfUnity(1/5, 3/2) 

doctest:...: DeprecationWarning: ANRootOfUnity is deprecated 

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

3/2*zeta5 where zeta5^4 + zeta5^3 + zeta5^2 + zeta5 + 1 = 0 

and zeta5 in 0.3090169943749474? + 0.9510565162951536?*I 

""" 

def __new__(self, a, b): 

from sage.misc.superseded import deprecation 

deprecation(19954, "ANRootOfUnity is deprecated") 

descr = QQbar.zeta(a.denominator())._descr 

generator = descr._generator 

value = b * descr._value ** (a.numerator()) 

return ANExtensionElement(generator, value)