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

r""" 

Rational Numbers 

  

AUTHORS: 

  

- William Stein (2005): first version 

  

- William Stein (2006-02-22): floor and ceil (pure fast GMP versions). 

  

- Gonzalo Tornaria and William Stein (2006-03-02): greatly improved 

python/GMP conversion; hashing 

  

- William Stein and Naqi Jaffery (2006-03-06): height, sqrt examples, 

and improve behavior of sqrt. 

  

- David Harvey (2006-09-15): added nth_root 

  

- Pablo De Napoli (2007-04-01): corrected the implementations of 

multiplicative_order, is_one; optimized __nonzero__ ; documented: 

lcm,gcd 

  

- John Cremona (2009-05-15): added support for local and global 

logarithmic heights. 

  

- Travis Scrimshaw (2012-10-18): Added doctests for full coverage. 

  

- Vincent Delecroix (2013): continued fraction 

  

- Vincent Delecroix (2017-05-03): faster integer-rational comparison 

  

- Vincent Klein (2017-05-11): add __mpq__() to class Rational 

  

- Vincent Klein (2017-05-22): Rational constructor support gmpy2.mpq 

or gmpy2.mpz parameter. Add __mpz__ to class Rational. 

  

TESTS:: 

  

sage: a = -2/3 

sage: a == loads(dumps(a)) 

True 

""" 

  

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

# Copyright (C) 2004, 2006 William Stein <wstein@gmail.com> 

# Copyright (C) 2017 Vincent Delecroix <20100.delecroix@gmail.com> 

# 

# Distributed under the terms of the GNU General Public License (GPL) 

# as published by the Free Software Foundation; either version 2 of 

# the License, or (at your option) any later version. 

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

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

  

from __future__ import absolute_import 

  

from cpython cimport * 

from cpython.object cimport Py_EQ, Py_NE 

  

from cysignals.signals cimport sig_on, sig_off 

  

import sys 

import operator 

import fractions 

  

from sage.misc.mathml import mathml 

from sage.arith.long cimport pyobject_to_long, integer_check_long_py 

from sage.cpython.string cimport char_to_str, str_to_bytes 

  

import sage.misc.misc as misc 

from sage.structure.sage_object cimport SageObject 

from sage.structure.richcmp cimport rich_to_bool_sgn 

import sage.rings.rational_field 

  

cimport sage.rings.integer as integer 

from .integer cimport Integer 

  

from cypari2.paridecl cimport * 

from cypari2.gen cimport Gen as pari_gen 

from sage.libs.pari.convert_gmp cimport INT_to_mpz, INTFRAC_to_mpq, new_gen_from_mpq_t 

  

from .integer_ring import ZZ 

from sage.arith.rational_reconstruction cimport mpq_rational_reconstruction 

  

from sage.structure.coerce cimport is_numpy_type 

  

from sage.libs.gmp.pylong cimport mpz_set_pylong 

  

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

from sage.structure.element import bin_op, coerce_binop 

from sage.structure.parent cimport Parent 

from sage.categories.morphism cimport Morphism 

from sage.categories.map cimport Map 

  

  

  

import sage.rings.real_mpfr 

import sage.rings.real_double 

from libc.stdint cimport uint64_t 

from sage.libs.gmp.binop cimport mpq_add_z, mpq_mul_z, mpq_div_zz 

  

from cpython.int cimport PyInt_AS_LONG 

  

cimport sage.rings.fast_arith 

import sage.rings.fast_arith 

  

cdef sage.rings.fast_arith.arith_int ai 

ai = sage.rings.fast_arith.arith_int() 

  

cdef object numpy_long_interface = {'typestr': '=i4' if sizeof(long) == 4 else '=i8' } 

cdef object numpy_int64_interface = {'typestr': '=i8'} 

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

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

  

from libc.math cimport ldexp 

from sage.libs.gmp.all cimport * 

  

IF HAVE_GMPY2: 

cimport gmpy2 

gmpy2.import_gmpy2() 

  

  

cdef class Rational(sage.structure.element.FieldElement) 

  

cdef inline void set_from_mpq(Rational self, mpq_t value): 

mpq_set(self.value, value) 

  

cdef inline void set_from_Rational(Rational self, Rational other): 

mpq_set(self.value, other.value) 

  

cdef inline void set_from_Integer(Rational self, integer.Integer other): 

mpq_set_z(self.value, other.value) 

  

cdef object Rational_mul_(Rational a, Rational b): 

cdef Rational x 

x = <Rational> Rational.__new__(Rational) 

  

sig_on() 

mpq_mul(x.value, a.value, b.value) 

sig_off() 

  

return x 

  

cdef object Rational_div_(Rational a, Rational b): 

cdef Rational x 

x = <Rational> Rational.__new__(Rational) 

  

sig_on() 

mpq_div(x.value, a.value, b.value) 

sig_off() 

  

return x 

  

cdef Rational_add_(Rational self, Rational other): 

cdef Rational x 

x = <Rational> Rational.__new__(Rational) 

sig_on() 

mpq_add(x.value, self.value, other.value) 

sig_off() 

return x 

  

cdef Rational_sub_(Rational self, Rational other): 

cdef Rational x 

x = <Rational> Rational.__new__(Rational) 

  

sig_on() 

mpq_sub(x.value, self.value, other.value) 

sig_off() 

  

return x 

  

cdef Parent the_rational_ring = sage.rings.rational_field.Q 

  

# make sure zero/one elements are set 

cdef set_zero_one_elements(): 

global the_rational_ring 

the_rational_ring._zero_element = Rational(0) 

the_rational_ring._one_element = Rational(1) 

  

set_zero_one_elements() 

  

cpdef Integer integer_rational_power(Integer a, Rational b): 

""" 

Compute `a^b` as an integer, if it is integral, or return ``None``. 

  

The nonnegative real root is taken for even denominators. 

  

INPUT: 

  

- a -- an ``Integer`` 

- b -- a nonnegative ``Rational`` 

  

OUTPUT: 

  

`a^b` as an ``Integer`` or ``None`` 

  

EXAMPLES:: 

  

sage: from sage.rings.rational import integer_rational_power 

sage: integer_rational_power(49, 1/2) 

7 

sage: integer_rational_power(27, 1/3) 

3 

sage: integer_rational_power(-27, 1/3) is None 

True 

sage: integer_rational_power(-27, 2/3) is None 

True 

sage: integer_rational_power(512, 7/9) 

128 

  

sage: integer_rational_power(27, 1/4) is None 

True 

sage: integer_rational_power(-16, 1/4) is None 

True 

  

sage: integer_rational_power(0, 7/9) 

0 

sage: integer_rational_power(1, 7/9) 

1 

sage: integer_rational_power(-1, 7/9) is None 

True 

sage: integer_rational_power(-1, 8/9) is None 

True 

sage: integer_rational_power(-1, 9/8) is None 

True 

  

TESTS (:trac:`11228`):: 

  

sage: integer_rational_power(-10, QQ(2)) 

100 

sage: integer_rational_power(0, QQ(0)) 

1 

""" 

cdef Integer z = Integer.__new__(Integer) 

if mpz_sgn(mpq_numref(b.value)) < 0: 

raise ValueError("Only positive exponents supported.") 

cdef int sgn = mpz_sgn(a.value) 

cdef bint exact 

if (mpz_cmp_ui(a.value, 1) == 0 or 

mpz_cmp_ui(mpq_numref(b.value), 0) == 0): 

mpz_set_ui(z.value, 1) 

elif sgn == 0: 

pass # z is 0 

elif sgn < 0 and mpz_cmp_ui(mpq_denref(b.value), 1): 

return None 

else: 

if (not mpz_fits_ulong_p(mpq_numref(b.value)) 

or not mpz_fits_ulong_p(mpq_denref(b.value))): 

# too big to take roots/powers 

return None 

elif mpz_cmp_ui(mpq_denref(b.value), 2) == 0: 

if mpz_perfect_square_p(a.value): 

mpz_sqrt(z.value, a.value) 

else: 

return None 

else: 

exact = mpz_root(z.value, a.value, mpz_get_ui(mpq_denref(b.value))) 

if not exact: 

return None 

mpz_pow_ui(z.value, z.value, mpz_get_ui(mpq_numref(b.value))) 

return z 

  

cpdef rational_power_parts(a, b, factor_limit=10**5): 

""" 

Compute rationals or integers `c` and `d` such that `a^b = c*d^b` 

with `d` small. This is used for simplifying radicals. 

  

INPUT: 

  

- ``a`` -- a rational or integer 

- ``b`` -- a rational 

- ``factor_limit`` -- the limit used in factoring ``a`` 

  

EXAMPLES:: 

  

sage: from sage.rings.rational import rational_power_parts 

sage: rational_power_parts(27, 1/2) 

(3, 3) 

sage: rational_power_parts(-128, 3/4) 

(8, -8) 

sage: rational_power_parts(-4, 1/2) 

(2, -1) 

sage: rational_power_parts(-4, 1/3) 

(1, -4) 

sage: rational_power_parts(9/1000, 1/2) 

(3/10, 1/10) 

  

TESTS: 

  

Check if :trac:`8540` is fixed:: 

  

sage: rational_power_parts(3/4, -1/2) 

(2, 3) 

sage: t = (3/4)^(-1/2); t 

2/3*sqrt(3) 

sage: t^2 

4/3 

  

Check if :trac:`15605` is fixed:: 

  

sage: rational_power_parts(-1, -1/3) 

(1, -1) 

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

-(-1)^(2/3) 

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

-(-1)^(2/3) 

sage: rational_power_parts(-1, 2/3) 

(1, -1) 

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

(-1)^(2/3) 

sage: all(rational_power_parts(-1, i/77) == (1,-1) for i in range(1,9)) 

True 

sage: (-1)^(1/3)*(-1)^(1/5) 

(-1)^(8/15) 

sage: bool((-1)^(2/3) == -1/2 + sqrt(3)/2*I) 

True 

sage: all((-1)^(p/q) == cos(p*pi/q) + I * sin(p*pi/q) for p in srange(1,6) for q in srange(1,6)) 

True 

""" 

b_negative=False 

if b < 0: 

b_negative = True 

b = -b 

a = ~a 

if isinstance(a, Rational): 

c1, d1 = rational_power_parts(a.numerator(), b) 

c2, d2 = rational_power_parts(a.denominator(), b) 

return (c1/c2, d1/d2) if not b_negative else (c1/c2, d2/d1) 

elif not isinstance(a, Integer): 

a = Integer(a) 

c = integer_rational_power(a, b) 

if c is not None: 

return c, 1 

numer, denom = b.numerator(), b.denominator() 

if a == -1 and denom > 1: 

return 1, -1 

if a < factor_limit*factor_limit: 

f = a.factor() 

else: 

from sage.rings.factorint import factor_trial_division 

f = factor_trial_division(a,factor_limit) 

c = 1 

d = 1 

for p, e in f: 

c *= p**((e // denom)*numer) 

d *= p**(e % denom) 

if a < 0 and numer & 1: 

d = -d 

return (c, d) if not b_negative else (c, ~d) 

  

  

def is_Rational(x): 

""" 

Return true if x is of the Sage rational number type. 

  

EXAMPLES:: 

  

sage: from sage.rings.rational import is_Rational 

sage: is_Rational(2) 

False 

sage: is_Rational(2/1) 

True 

sage: is_Rational(int(2)) 

False 

sage: is_Rational(long(2)) 

False 

sage: is_Rational('5') 

False 

""" 

return isinstance(x, Rational) 

  

  

cdef class Rational(sage.structure.element.FieldElement): 

""" 

A rational number. 

  

Rational numbers are implemented using the GMP C library. 

  

EXAMPLES:: 

  

sage: a = -2/3 

sage: type(a) 

<type 'sage.rings.rational.Rational'> 

sage: parent(a) 

Rational Field 

sage: Rational('1/0') 

Traceback (most recent call last): 

... 

TypeError: unable to convert '1/0' to a rational 

sage: Rational(1.5) 

3/2 

sage: Rational('9/6') 

3/2 

sage: Rational((2^99,2^100)) 

1/2 

sage: Rational(("2", "10"), 16) 

1/8 

sage: Rational(QQbar(125/8).nth_root(3)) 

5/2 

sage: Rational(AA(209735/343 - 17910/49*golden_ratio).nth_root(3) + 3*AA(golden_ratio)) 

53/7 

sage: QQ(float(1.5)) 

3/2 

sage: QQ(RDF(1.2)) 

6/5 

  

Conversion from fractions:: 

  

sage: import fractions 

sage: f = fractions.Fraction(1r, 2r) 

sage: Rational(f) 

1/2 

  

Conversion from PARI:: 

  

sage: Rational(pari('-939082/3992923')) 

-939082/3992923 

sage: Rational(pari('Pol([-1/2])')) #9595 

-1/2 

  

Conversions from numpy:: 

  

sage: import numpy as np 

sage: QQ(np.int8('-15')) 

-15 

sage: QQ(np.int16('-32')) 

-32 

sage: QQ(np.int32('-19')) 

-19 

sage: QQ(np.uint32('1412')) 

1412 

  

sage: QQ(np.float16('12')) 

12 

  

Conversions from gmpy2:: 

  

sage: from gmpy2 import * # optional - gmpy2 

sage: QQ(mpq('3/4')) # optional - gmpy2 

3/4 

sage: QQ(mpz(42)) # optional - gmpy2 

42 

sage: Rational(mpq(2/3)) # optional - gmpy2 

2/3 

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

5 

""" 

def __cinit__(self): 

r""" 

Initialize ``self`` as an element of `\QQ`. 

  

EXAMPLES:: 

  

sage: p = Rational(3) # indirect doctest 

sage: p.parent() 

Rational Field 

""" 

global the_rational_ring 

mpq_init(self.value) 

self._parent = the_rational_ring 

  

def __init__(self, x=None, unsigned int base=0): 

""" 

Create a new rational number. 

  

INPUT: 

  

- ``x`` - object (default: ``None``) 

  

- ``base`` - base if ``x`` is a string 

  

EXAMPLES:: 

  

sage: a = Rational() 

sage: a.__init__(7); a 

7 

sage: a.__init__('70', base=8); a 

56 

sage: a.__init__(pari('2/3')); a 

2/3 

sage: a.__init__('-h/3ki', 32); a 

-17/3730 

sage: from gmpy2 import mpq # optional - gmpy2 

sage: a.__init__(mpq('3/5')); a # optional - gmpy2 

3/5 

  

TESTS: 

  

Check that :trac:`19835` is fixed:: 

  

sage: QQ((0r,-1r)) 

0 

sage: QQ((-1r,-1r)) 

1 

  

.. NOTE:: 

  

This is for demonstration purposes only, mutating rationals 

is almost always the wrong thing to do. 

""" 

if x is not None: 

self.__set_value(x, base) 

  

def __reduce__(self): 

""" 

Used in pickling rational numbers. 

  

EXAMPLES:: 

  

sage: a = 3/5 

sage: a.__reduce__() 

(<built-in function make_rational>, ('3/5',)) 

""" 

return sage.rings.rational.make_rational, (self.str(32),) 

  

def __index__(self): 

""" 

Needed so integers can be used as list indices. 

  

EXAMPLES:: 

  

sage: v = [1,2,3,4,5] 

sage: v[3/1] 

4 

sage: v[3/2] 

Traceback (most recent call last): 

... 

TypeError: rational is not an integer 

""" 

if self.denominator() == 1: 

return int(self) 

raise TypeError("rational is not an integer") 

  

def _reduce_set(self, s): 

""" 

Used in setting a rational number when unpickling. Do not call this 

from external code since it violates immutability. 

  

INPUT: 

  

- ``s`` - string representation of rational in base 32 

  

EXAMPLES:: 

  

sage: a = -17/3730; _, (s,) = a.__reduce__(); s 

'-h/3ki' 

sage: b = 2/3; b._reduce_set('-h/3ki'); b 

-17/3730 

  

sage: Rational(pari(-345/7687)) 

-345/7687 

sage: Rational(pari(-345)) 

-345 

sage: Rational(pari('Mod(2,3)')) 

2 

sage: Rational(pari('x')) 

Traceback (most recent call last): 

... 

TypeError: Unable to coerce PARI x to an Integer 

""" 

mpq_set_str(self.value, str_to_bytes(s), 32) 

  

cdef __set_value(self, x, unsigned int base): 

cdef int n 

cdef Rational temp_rational 

cdef integer.Integer a, b 

  

if isinstance(x, Rational): 

set_from_Rational(self, x) 

  

elif isinstance(x, long): 

mpz_set_pylong(mpq_numref(self.value), x) 

  

elif isinstance(x, int): 

i = x 

mpq_set_si(self.value, i, 1) 

  

elif isinstance(x, integer.Integer): 

set_from_Integer(self, x) 

  

elif isinstance(x, sage.rings.real_mpfr.RealNumber): 

  

if x == 0: 

mpq_set_si(self.value, 0, 1) 

return 

if not base: 

set_from_Rational(self, x.simplest_rational()) 

else: 

# Truncate in base 10 to match repr(x). 

# See https://trac.sagemath.org/ticket/21124 

xstr = x.str(base, truncate=(base == 10)) 

if '.' in xstr: 

exp = (len(xstr) - (xstr.index('.') +1)) 

p = base**exp 

pstr = '1'+'0'*exp 

s = xstr.replace('.','') +'/'+pstr 

n = mpq_set_str(self.value, str_to_bytes(s), base) 

if n or mpz_cmp_si(mpq_denref(self.value), 0) == 0: 

raise TypeError("unable to convert {!r} to a rational".format(x)) 

mpq_canonicalize(self.value) 

else: 

n = mpq_set_str(self.value, xstr, base) 

if n or mpz_cmp_si(mpq_denref(self.value), 0) == 0: 

raise TypeError("unable to convert {!r} to a rational".format(x)) 

mpq_canonicalize(self.value) 

elif isinstance(x, bytes): 

n = mpq_set_str(self.value, x, base) 

if n or mpz_cmp_si(mpq_denref(self.value), 0) == 0: 

raise TypeError("unable to convert {!r} to a rational".format(x)) 

mpq_canonicalize(self.value) 

elif isinstance(x, unicode): 

n = mpq_set_str(self.value, str_to_bytes(x), base) 

if n or mpz_cmp_si(mpq_denref(self.value), 0) == 0: 

raise TypeError("unable to convert {!r} to a rational".format(x)) 

mpq_canonicalize(self.value) 

  

elif hasattr(x, "_rational_"): 

set_from_Rational(self, x._rational_()) 

  

elif isinstance(x, tuple) and len(x) == 2: 

num = x[0] 

denom = x[1] 

if isinstance(num, int) and isinstance(denom, int): 

if denom >= 0: 

mpq_set_si(self.value, num, denom) 

else: 

mpq_set_si(self.value, -num, -denom) 

else: 

if not isinstance(num, integer.Integer): 

num = integer.Integer(num, base) 

if not isinstance(denom, integer.Integer): 

denom = integer.Integer(denom, base) 

mpz_set(mpq_numref(self.value), (<integer.Integer>num).value) 

mpz_set(mpq_denref(self.value), (<integer.Integer>denom).value) 

if mpz_sgn(mpq_denref(self.value)) == 0: 

raise ValueError("denominator must not be 0") 

mpq_canonicalize(self.value) 

  

elif isinstance(x, pari_gen): 

x = x.simplify() 

if is_rational_t(typ((<pari_gen>x).g)): 

INTFRAC_to_mpq(self.value, (<pari_gen>x).g) 

else: 

a = integer.Integer(x) 

mpz_set(mpq_numref(self.value), a.value) 

mpz_set_si(mpq_denref(self.value), 1) 

  

elif isinstance(x, list) and len(x) == 1: 

self.__set_value(x[0], base) 

  

elif hasattr(x, 'rational_reconstruction'): 

temp_rational = x.rational_reconstruction() 

mpq_set(self.value, temp_rational.value) 

  

elif isinstance(x, (float, sage.rings.real_double.RealDoubleElement)): 

self.__set_value(sage.rings.real_mpfr.RealNumber(sage.rings.real_mpfr.RR, x), base) 

  

elif is_numpy_type(type(x)): 

import numpy 

if isinstance(x, numpy.integer): 

self.__set_value(integer.Integer(x), base) 

elif isinstance(x, numpy.floating): 

self.__set_value(sage.rings.real_mpfr.RR(x), base) 

else: 

raise TypeError("unable to convert {!r} to a rational".format(x)) 

  

elif isinstance(x, fractions.Fraction): 

mpz_set(mpq_numref(self.value), (<integer.Integer> integer.Integer(x.numerator)).value) 

mpz_set(mpq_denref(self.value), (<integer.Integer> integer.Integer(x.denominator)).value) 

  

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

mpq_set(self.value, (<gmpy2.mpq>x).q) 

  

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

mpq_set_z(self.value, (<gmpy2.mpz>x).z) 

  

else: 

raise TypeError("unable to convert {!r} to a rational".format(x)) 

  

cdef void set_from_mpq(Rational self, mpq_t value): 

mpq_set(self.value, value) 

  

def list(self): 

""" 

Return a list with the rational element in it, to be compatible 

with the method for number fields. 

  

OUTPUT: 

  

- ``list`` - the list ``[self]`` 

  

EXAMPLES:: 

  

sage: m = 5/3 

sage: m.list() 

[5/3] 

""" 

return [ self ] 

  

def continued_fraction_list(self, type="std"): 

r""" 

Return the list of partial quotients of this rational number. 

  

INPUT: 

  

- ``type`` - either "std" (the default) for the standard continued 

fractions or "hj" for the Hirzebruch-Jung ones. 

  

EXAMPLES:: 

  

sage: (13/9).continued_fraction_list() 

[1, 2, 4] 

sage: 1 + 1/(2 + 1/4) 

13/9 

  

sage: (225/157).continued_fraction_list() 

[1, 2, 3, 4, 5] 

sage: 1 + 1/(2 + 1/(3 + 1/(4 + 1/5))) 

225/157 

  

sage: (fibonacci(20)/fibonacci(19)).continued_fraction_list() 

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2] 

  

sage: (-1/3).continued_fraction_list() 

[-1, 1, 2] 

  

Check that the partial quotients of an integer ``n`` is simply ``[n]``:: 

  

sage: QQ(1).continued_fraction_list() 

[1] 

sage: QQ(0).continued_fraction_list() 

[0] 

sage: QQ(-1).continued_fraction_list() 

[-1] 

  

Hirzebruch-Jung continued fractions:: 

  

sage: (11/19).continued_fraction_list("hj") 

[1, 3, 2, 3, 2] 

sage: 1 - 1/(3 - 1/(2 - 1/(3 - 1/2))) 

11/19 

  

sage: (225/137).continued_fraction_list("hj") 

[2, 3, 5, 10] 

sage: 2 - 1/(3 - 1/(5 - 1/10)) 

225/137 

  

sage: (-23/19).continued_fraction_list("hj") 

[-1, 5, 4] 

sage: -1 - 1/(5 - 1/4) 

-23/19 

""" 

cdef Integer z 

cdef mpz_t p,q,tmp 

cdef list res = [] 

  

mpz_init(tmp) 

mpz_init(p) 

mpz_init(q) 

mpz_set(p, mpq_numref(self.value)) 

mpz_set(q, mpq_denref(self.value)) 

  

if type == "std": 

while mpz_sgn(q) != 0: 

z = Integer.__new__(Integer) 

mpz_fdiv_qr(z.value,tmp,p,q) 

mpz_set(p,q) 

mpz_set(q,tmp) 

res.append(z) 

elif type == "hj": 

while mpz_sgn(q) != 0: 

z = Integer.__new__(Integer) 

mpz_cdiv_qr(z.value,tmp,p,q) 

mpz_set(p,q) 

mpz_set(q,tmp) 

res.append(z) 

if mpz_sgn(q) == 0: 

break 

z = Integer.__new__(Integer) 

mpz_fdiv_qr(z.value,tmp,p,q) 

mpz_set(p,q) 

mpz_set(q,tmp) 

mpz_neg(z.value,z.value) 

res.append(z) 

else: 

mpz_clear(p) 

mpz_clear(q) 

mpz_clear(tmp) 

raise ValueError("the type must be one of 'floor', 'hj'") 

  

mpz_clear(p) 

mpz_clear(q) 

mpz_clear(tmp) 

  

return res 

  

def continued_fraction(self): 

r""" 

Return the continued fraction of that rational. 

  

EXAMPLES:: 

  

sage: (641/472).continued_fraction() 

[1; 2, 1, 3, 1, 4, 1, 5] 

  

sage: a = (355/113).continued_fraction(); a 

[3; 7, 16] 

sage: a.n(digits=10) 

3.141592920 

sage: pi.n(digits=10) 

3.141592654 

  

It's almost pi! 

""" 

#TODO: do better 

from sage.rings.continued_fraction import ContinuedFraction_periodic 

l = self.continued_fraction_list() 

return ContinuedFraction_periodic(l) 

  

def __richcmp__(left, right, int op): 

""" 

Compare two rational numbers. 

  

INPUT: 

  

- ``left, right`` -- objects 

  

- ``op`` -- integer 

  

EXAMPLES:: 

  

sage: 1/3 < 2/3 

True 

sage: 2/3 < 1/3 

False 

sage: 4/5 < 2.0 

True 

sage: 4/5 < 0.8 

False 

  

sage: ones = [1, 1r, 1l, 1/1, 1.0r, 1.0] 

sage: twos = [2, 2r, 2l, 2/1, 2.0r, 2.0] 

sage: threes = [3, 3r, 3l, 3/1, 3.0r, 3.0] 

sage: from itertools import product 

sage: for one,two,three in product(ones,twos,threes): 

....: assert one < two < three 

....: assert one <= two <= three 

....: assert three > two > one 

....: assert three >= two >= one 

....: assert one != two and one != three and two != three 

sage: for one1, one2 in product(ones,repeat=2): 

....: assert (one1 == one2) is True 

....: assert (one1 <= one2) is True 

....: assert (one1 >= one2) is True 

""" 

cdef int c 

cdef mpz_t mpz_tmp 

  

assert isinstance(left, Rational) 

  

if isinstance(right, Rational): 

if op == Py_EQ: 

return <bint> mpq_equal((<Rational>left).value, (<Rational>right).value) 

elif op == Py_NE: 

return not mpq_equal((<Rational>left).value, (<Rational>right).value) 

else: 

c = mpq_cmp((<Rational>left).value, (<Rational>right).value) 

elif isinstance(right, Integer): 

c = mpq_cmp_z((<Rational>left).value, (<Integer>right).value) 

elif isinstance(right, long): 

mpz_init(mpz_tmp) 

mpz_set_pylong(mpz_tmp, right) 

c = mpq_cmp_z((<Rational>left).value, mpz_tmp) 

mpz_clear(mpz_tmp) 

elif isinstance(right, int): 

c = mpq_cmp_si((<Rational>left).value, PyInt_AS_LONG(right), 1) 

else: 

return coercion_model.richcmp(left, right, op) 

  

return rich_to_bool_sgn(op, c) 

  

cpdef int _cmp_(left, right) except -2: 

r""" 

TESTS:: 

  

sage: (2/3)._cmp_(3/4) 

-1 

sage: (1/2)._cmp_(1/2) 

0 

""" 

cdef int c 

c = mpq_cmp((<Rational>left).value, (<Rational>right).value) 

return (c > 0) - (c < 0) 

  

def __copy__(self): 

""" 

Return a copy of ``self``. 

  

OUTPUT: Rational 

  

EXAMPLES:: 

  

sage: a = -17/37 

sage: copy(a) is a 

False 

  

Coercion does not make a new copy:: 

  

sage: QQ(a) is a 

True 

  

The constructor also makes a new copy:: 

  

sage: Rational(a) is a 

False 

""" 

cdef Rational z 

z = <Rational> Rational.__new__(Rational) 

mpq_set(z.value, self.value) 

return z 

  

def __dealloc__(self): 

""" 

Free memory occupied by this rational number. 

  

EXAMPLES:: 

  

sage: a = -17/37 

sage: del a # indirect test 

""" 

mpq_clear(self.value) 

  

def __repr__(self): 

""" 

Return string representation of this rational number. 

  

EXAMPLES:: 

  

sage: a = -17/37; a.__repr__() 

'-17/37' 

""" 

return self.str() 

  

def _latex_(self): 

""" 

Return Latex representation of this rational number. 

  

EXAMPLES:: 

  

sage: a = -17/37 

sage: a._latex_() 

'-\\frac{17}{37}' 

""" 

if self.denom() == 1: 

return str(self.numer()) 

else: 

if self < 0: 

return "-\\frac{%s}{%s}"%(-self.numer(), self.denom()) 

else: 

return "\\frac{%s}{%s}"%(self.numer(), self.denom()) 

  

def _sympy_(self): 

""" 

Convert Sage ``Rational`` to SymPy ``Rational``. 

  

EXAMPLES:: 

  

sage: n = 1/2; n._sympy_() 

1/2 

sage: n = -1/5; n._sympy_() 

-1/5 

sage: from sympy import Symbol 

sage: QQ(1)+Symbol('x')*QQ(2) 

2*x + 1 

""" 

import sympy 

return sympy.Rational(int(self.numerator()), int(self.denominator())) 

  

def __mpz__(self): 

""" 

Return a gmpy2 ``mpz`` if this Rational is an integer. 

  

EXAMPLES:: 

  

sage: q = 6/2 

sage: q.__mpz__() # optional - gmpy2 

mpz(3) 

sage: q = 1/4 

sage: q.__mpz__() # optional - gmpy2 

Traceback (most recent call last): 

... 

TypeError: rational is not an integer 

  

TESTS:: 

  

sage: QQ().__mpz__(); raise NotImplementedError("gmpy2 is not installed") 

Traceback (most recent call last): 

... 

NotImplementedError: gmpy2 is not installed 

""" 

if self.denominator() != 1: 

raise TypeError("rational is not an integer") 

return self.numerator().__mpz__() 

  

def __mpq__(self): 

""" 

Convert Sage ``Rational`` to gmpy2 ``Rational``. 

  

EXAMPLES:: 

  

sage: r = 5/3 

sage: r.__mpq__() # optional - gmpy2 

mpq(5,3) 

sage: from gmpy2 import mpq # optional - gmpy2 

sage: mpq(r) # optional - gmpy2 

mpq(5,3) 

  

TESTS:: 

  

sage: r.__mpq__(); raise NotImplementedError("gmpy2 is not installed") 

Traceback (most recent call last): 

... 

NotImplementedError: gmpy2 is not installed 

""" 

IF HAVE_GMPY2: 

return gmpy2.GMPy_MPQ_From_mpq(self.value) 

ELSE: 

raise NotImplementedError("gmpy2 is not installed") 

  

def _magma_init_(self, magma): 

""" 

Return the magma representation of ``self``. 

  

EXAMPLES:: 

  

sage: n = -485/82847 

sage: n._magma_init_(magma) # optional - magma 

'-485/82847' 

""" 

return self.numerator()._magma_init_(magma) + '/' + self.denominator()._magma_init_(magma) 

  

@property 

def __array_interface__(self): 

""" 

Used for NumPy conversion. If ``self`` is integral, it converts to 

an ``Integer``. Otherwise it converts to a double floating point 

value. 

  

EXAMPLES:: 

  

sage: import numpy 

sage: numpy.array([1, 2, 3/1]) 

array([1, 2, 3]) 

  

sage: numpy.array(QQ(2**40)).dtype 

dtype('int64') 

sage: numpy.array(QQ(2**400)).dtype 

dtype('O') 

  

sage: numpy.array([1, 1/2, 3/4]) 

array([ 1. , 0.5 , 0.75]) 

""" 

if mpz_cmp_ui(mpq_denref(self.value), 1) == 0: 

if mpz_fits_slong_p(mpq_numref(self.value)): 

return numpy_long_interface 

elif sizeof(long) == 4 and mpz_sizeinbase(mpq_numref(self.value), 2) <= 63: 

return numpy_int64_interface 

else: 

return numpy_object_interface 

else: 

return numpy_double_interface 

  

def _mathml_(self): 

""" 

Return mathml representation of this rational number. 

  

EXAMPLES:: 

  

sage: a = -17/37; a._mathml_() 

'<mo>-</mo><mfrac><mrow><mn>17</mn></mrow><mrow><mn>37</mn></mrow></mfrac>' 

""" 

if self.denom() == 1: 

return '<mn>%s</mn>'%(self.numer()) 

else: 

t = '' 

if self < 0: 

t = t + '<mo>-</mo>' 

t = t + '<mfrac><mrow>%s</mrow><mrow>%s</mrow></mfrac>'%( 

mathml(abs(self.numer())), mathml(self.denom())) 

return t 

  

def _im_gens_(self, codomain, im_gens): 

""" 

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

field to ``codomain``. 

  

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

  

INPUT: 

  

- ``codomain`` -- object (usually a ring) 

  

- ``im_gens`` -- list of elements of ``codomain`` 

  

EXAMPLES:: 

  

sage: a = -17/37 

sage: a._im_gens_(QQ, [1/1]) 

-17/37 

""" 

return codomain._coerce_(self) 

  

def content(self, other): 

""" 

Return the content of ``self`` and ``other``, i.e. the unique positive 

rational number `c` such that ``self/c`` and ``other/c`` are coprime 

integers. 

  

``other`` can be a rational number or a list of rational numbers. 

  

EXAMPLES:: 

  

sage: a = 2/3 

sage: a.content(2/3) 

2/3 

sage: a.content(1/5) 

1/15 

sage: a.content([2/5, 4/9]) 

2/45 

""" 

from sage.structure.sequence import Sequence 

seq = Sequence(other) 

seq.append(self) 

nums = [x.numerator() for x in seq] 

denoms = [x.denominator() for x in seq] 

from sage.arith.all import gcd, lcm 

return gcd(nums) / lcm(denoms) 

  

def valuation(self, p): 

r""" 

Return the power of ``p`` in the factorization of self. 

  

INPUT: 

  

  

- ``p`` - a prime number 

  

OUTPUT: 

  

(integer or infinity) ``Infinity`` if ``self`` is zero, otherwise the 

(positive or negative) integer `e` such that ``self`` = `m*p^e` 

with `m` coprime to `p`. 

  

.. NOTE:: 

  

See also :meth:`val_unit()` which returns the pair `(e,m)`. The 

function :meth:`ord()` is an alias for :meth:`valuation()`. 

  

EXAMPLES:: 

  

sage: x = -5/9 

sage: x.valuation(5) 

1 

sage: x.ord(5) 

1 

sage: x.valuation(3) 

-2 

sage: x.valuation(2) 

0 

  

Some edge cases:: 

  

sage: (0/1).valuation(4) 

+Infinity 

sage: (7/16).valuation(4) 

-2 

""" 

return self.numerator().valuation(p) - self.denominator().valuation(p) 

  

ord = valuation 

  

def local_height(self, p, prec=None): 

r""" 

Returns the local height of this rational number at the prime `p`. 

  

INPUT: 

  

- ``p`` -- a prime number 

  

- ``prec`` (int) -- desired floating point precision (default: 

default RealField precision). 

  

OUTPUT: 

  

(real) The local height of this rational number at the 

prime `p`. 

  

EXAMPLES:: 

  

sage: a = QQ(25/6) 

sage: a.local_height(2) 

0.693147180559945 

sage: a.local_height(3) 

1.09861228866811 

sage: a.local_height(5) 

0.000000000000000 

""" 

from sage.rings.real_mpfr import RealField 

if prec is None: 

R = RealField() 

else: 

R = RealField(prec) 

if self.is_zero(): 

return R.zero() 

val = self.valuation(p) 

if val >= 0: 

return R.zero() 

return -val * R(p).log() 

  

def local_height_arch(self, prec=None): 

r""" 

Returns the Archimedean local height of this rational number at the 

infinite place. 

  

INPUT: 

  

- ``prec`` (int) -- desired floating point precision (default: 

default RealField precision). 

  

OUTPUT: 

  

(real) The local height of this rational number `x` at the 

unique infinite place of `\QQ`, which is 

`\max(\log(|x|),0)`. 

  

EXAMPLES:: 

  

sage: a = QQ(6/25) 

sage: a.local_height_arch() 

0.000000000000000 

sage: (1/a).local_height_arch() 

1.42711635564015 

sage: (1/a).local_height_arch(100) 

1.4271163556401457483890413081 

""" 

from sage.rings.real_mpfr import RealField 

if prec is None: 

R = RealField() 

else: 

R = RealField(prec) 

a = self.abs() 

if a <= 1: 

return R.zero() 

return R(a).log() 

  

def global_height_non_arch(self, prec=None): 

r""" 

Returns the total non-archimedean component of the height of this 

rational number. 

  

INPUT: 

  

- ``prec`` (int) -- desired floating point precision (default: 

default RealField precision). 

  

OUTPUT: 

  

(real) The total non-archimedean component of the height of 

this rational number. 

  

ALGORITHM: 

  

This is the sum of the local heights at all primes `p`, which 

may be computed without factorization as the log of the 

denominator. 

  

EXAMPLES:: 

  

sage: a = QQ(5/6) 

sage: a.support() 

[2, 3, 5] 

sage: a.global_height_non_arch() 

1.79175946922805 

sage: [a.local_height(p) for p in a.support()] 

[0.693147180559945, 1.09861228866811, 0.000000000000000] 

sage: sum([a.local_height(p) for p in a.support()]) 

1.79175946922805 

""" 

from sage.rings.real_mpfr import RealField 

if prec is None: 

R = RealField() 

else: 

R = RealField(prec) 

d = self.denominator() 

if d.is_one(): 

return R.zero() 

return R(d).log() 

  

def global_height_arch(self, prec=None): 

r""" 

Returns the total archimedean component of the height of this rational 

number. 

  

INPUT: 

  

- ``prec`` (int) -- desired floating point precision (default: 

default RealField precision). 

  

OUTPUT: 

  

(real) The total archimedean component of the height of 

this rational number. 

  

ALGORITHM: 

  

Since `\QQ` has only one infinite place this is just the value 

of the local height at that place. This separate function is 

included for compatibility with number fields. 

  

EXAMPLES:: 

  

sage: a = QQ(6/25) 

sage: a.global_height_arch() 

0.000000000000000 

sage: (1/a).global_height_arch() 

1.42711635564015 

sage: (1/a).global_height_arch(100) 

1.4271163556401457483890413081 

""" 

return self.local_height_arch(prec) 

  

def global_height(self, prec=None): 

r""" 

Returns the absolute logarithmic height of this rational number. 

  

INPUT: 

  

- ``prec`` (int) -- desired floating point precision (default: 

default RealField precision). 

  

OUTPUT: 

  

(real) The absolute logarithmic height of this rational number. 

  

ALGORITHM: 

  

The height is the sum of the total archimedean and 

non-archimedean components, which is equal to 

`\max(\log(n),\log(d))` where `n,d` are the numerator and 

denominator of the rational number. 

  

EXAMPLES:: 

  

sage: a = QQ(6/25) 

sage: a.global_height_arch() + a.global_height_non_arch() 

3.21887582486820 

sage: a.global_height() 

3.21887582486820 

sage: (1/a).global_height() 

3.21887582486820 

sage: QQ(0).global_height() 

0.000000000000000 

sage: QQ(1).global_height() 

0.000000000000000 

""" 

from sage.rings.real_mpfr import RealField 

if prec is None: 

R = RealField() 

else: 

R = RealField(prec) 

return R(max(self.numerator().abs(),self.denominator())).log() 

  

def is_square(self): 

""" 

Return whether or not this rational number is a square. 

  

OUTPUT: bool 

  

EXAMPLES:: 

  

sage: x = 9/4 

sage: x.is_square() 

True 

sage: x = (7/53)^100 

sage: x.is_square() 

True 

sage: x = 4/3 

sage: x.is_square() 

False 

sage: x = -1/4 

sage: x.is_square() 

False 

""" 

return mpq_sgn(self.value) >= 0 and mpz_perfect_square_p(mpq_numref(self.value)) and mpz_perfect_square_p(mpq_denref(self.value)) 

  

def is_norm(self, L, element=False, proof=True): 

r""" 

Determine whether ``self`` is the norm of an element of ``L``. 

  

INPUT: 

  

- ``L`` -- a number field 

- ``element`` -- (default: ``False``) boolean whether to also output 

an element of which ``self`` is a norm 

- proof -- If ``True``, then the output is correct unconditionally. 

If ``False``, then the output assumes GRH. 

  

OUTPUT: 

  

If element is ``False``, then the output is a boolean ``B``, which is 

``True`` if and only if ``self`` is the norm of an element of ``L``. 

If ``element`` is ``False``, then the output is a pair ``(B, x)``, 

where ``B`` is as above. If ``B`` is ``True``, then ``x`` an element of 

``L`` such that ``self == x.norm()``. Otherwise, ``x is None``. 

  

ALGORITHM: 

  

Uses PARI's bnfisnorm. See ``_bnfisnorm()``. 

  

EXAMPLES:: 

  

sage: K = NumberField(x^2 - 2, 'beta') 

sage: (1/7).is_norm(K) 

True 

sage: (1/10).is_norm(K) 

False 

sage: 0.is_norm(K) 

True 

sage: (1/7).is_norm(K, element=True) 

(True, 1/7*beta + 3/7) 

sage: (1/10).is_norm(K, element=True) 

(False, None) 

sage: (1/691).is_norm(QQ, element=True) 

(True, 1/691) 

  

The number field doesn't have to be defined by an 

integral polynomial:: 

  

sage: B, e = (1/5).is_norm(QuadraticField(5/4, 'a'), element=True) 

sage: B 

True 

sage: e.norm() 

1/5 

  

A non-Galois number field:: 

  

sage: K.<a> = NumberField(x^3-2) 

sage: B, e = (3/5).is_norm(K, element=True); B 

True 

sage: e.norm() 

3/5 

  

sage: 7.is_norm(K) 

Traceback (most recent call last): 

... 

NotImplementedError: is_norm is not implemented unconditionally for norms from non-Galois number fields 

sage: 7.is_norm(K, proof=False) 

False 

  

AUTHORS: 

  

- Craig Citro (2008-04-05) 

  

- Marco Streng (2010-12-03) 

""" 

if not element: 

return self.is_norm(L, element=True, proof=proof)[0] 

  

from sage.rings.number_field.number_field_base import is_NumberField 

if not is_NumberField(L): 

raise ValueError("L (=%s) must be a NumberField in is_norm" % L) 

if L.degree() == 1 or self.is_zero(): 

return True, L(self) 

d = L.polynomial().denominator() 

if not d == 1: 

M, M_to_L = L.subfield(L.gen()*d) 

b, x = self.is_norm(M, element=True, proof=proof) 

if b: 

x = M_to_L(x) 

return b, x 

a, b = self._bnfisnorm(L, proof=proof) 

if b == 1: 

assert a.norm() == self 

return True, a 

if L.is_galois(): 

return False, None 

M = L.galois_closure('a') 

from sage.functions.log import log 

from sage.functions.other import floor 

extra_primes = floor(12*log(abs(M.discriminant()))**2) 

a, b = self._bnfisnorm(L, proof=proof, extra_primes=extra_primes) 

if b == 1: 

assert a.norm() == self 

return True, a 

if proof: 

raise NotImplementedError("is_norm is not implemented unconditionally for norms from non-Galois number fields") 

return False, None 

  

def _bnfisnorm(self, K, proof=True, extra_primes=0): 

r""" 

This gives the output of the PARI function :pari:`bnfisnorm`. 

  

Tries to tell whether the rational number ``self`` is the norm of some 

element `y` in ``K``. Returns a pair `(a, b)` where 

``self = Norm(a)*b``. Looks for a solution that is an `S`-unit, with 

`S` a certain set of prime ideals containing (among others) all primes 

dividing ``self``. 

  

If `K` is known to be Galois, set ``extra_primes = 0`` (in this case, 

``self`` is a norm iff `b = 1`). 

  

If ``extra_primes`` is non-zero, the program adds to `S` the following 

prime ideals, depending on the sign of extra_primes. 

If ``extra_primes > 0``, the ideals of norm less than ``extra_primes``. 

And if ``extra_primes < 0``, the ideals dividing ``extra_primes``. 

  

Assuming GRH, the answer is guaranteed (i.e., ``self`` is a norm 

iff `b = 1`), if `S` contains all primes less than 

`12\log(\disc(L))^2`, 

where `L` is the Galois closure of `K`. 

  

INPUT: 

  

- ``K`` -- a number field 

- ``proof`` -- whether to certify the output of bnfinit. 

If ``False``, then correctness of the output depends on GRH. 

- ``extra_primes`` -- an integer as explained above 

  

OUTPUT: 

  

A pair `(a, b)` with `a` in `K` and `b` in `\QQ` such that 

``self == Norm(a)*b`` as explained above. 

  

ALGORITHM: 

  

Uses PARI's bnfisnorm. 

  

EXAMPLES:: 

  

sage: QQ(2)._bnfisnorm(QuadraticField(-1, 'i')) 

(i + 1, 1) 

sage: 7._bnfisnorm(NumberField(x^3-2, 'b')) 

(1, 7) 

  

AUTHORS: 

  

- Craig Citro (2008-04-05) 

  

- Marco Streng (2010-12-03) 

""" 

from sage.rings.number_field.number_field_base import is_NumberField 

if not is_NumberField(K): 

raise ValueError("K must be a NumberField in bnfisnorm") 

  

a, b = K.pari_bnf(proof=proof).bnfisnorm(self, flag=extra_primes) 

return K(a), Rational(b) 

  

  

def is_perfect_power(self, expected_value=False): 

r""" 

Returns ``True`` if ``self`` is a perfect power. 

  

INPUT: 

  

- ``expected_value`` - (bool) whether or not this rational is expected 

be a perfect power. This does not affect the correctness of the 

output, only the runtime. 

  

If ``expected_value`` is ``False`` (default) it will check the 

smallest of the numerator and denominator is a perfect power 

as a first step, which is often faster than checking if the 

quotient is a perfect power. 

  

EXAMPLES:: 

  

sage: (4/9).is_perfect_power() 

True 

sage: (144/1).is_perfect_power() 

True 

sage: (4/3).is_perfect_power() 

False 

sage: (2/27).is_perfect_power() 

False 

sage: (4/27).is_perfect_power() 

False 

sage: (-1/25).is_perfect_power() 

False 

sage: (-1/27).is_perfect_power() 

True 

sage: (0/1).is_perfect_power() 

True 

  

The second parameter does not change the result, but may 

change the runtime. 

  

:: 

  

sage: (-1/27).is_perfect_power(True) 

True 

sage: (-1/25).is_perfect_power(True) 

False 

sage: (2/27).is_perfect_power(True) 

False 

sage: (144/1).is_perfect_power(True) 

True 

  

This test makes sure we workaround a bug in GMP (see :trac:`4612`):: 

  

sage: [ -a for a in srange(100) if not QQ(-a^3).is_perfect_power() ] 

[] 

sage: [ -a for a in srange(100) if not QQ(-a^3).is_perfect_power(True) ] 

[] 

""" 

cdef int s 

  

if (mpz_cmp_ui(mpq_numref(self.value), 0) == 0): 

return True 

elif (mpz_cmp_ui(mpq_numref(self.value), 1) == 0): 

return mpz_perfect_power_p(mpq_denref(self.value)) 

  

cdef mpz_t prod 

cdef bint res 

  

# We should be able to run the code in the sign == 1 case 

# below for both cases. However, we need to do extra work to 

# avoid a bug in GMP's mpz_perfect_power_p; see trac #4612 for 

# more details. 

# 

# The code in the case of sign == -1 could definitely be 

# cleaned up, but it will be removed shortly, since both GMP 

# and eMPIRe have fixes for the mpz_perfect_power_p bug. 

  

s = mpz_sgn(mpq_numref(self.value)) 

if s == 1: # self is positive 

  

if (mpz_cmp_ui(mpq_denref(self.value), 1) == 0): 

return mpz_perfect_power_p(mpq_numref(self.value)) 

if not expected_value: 

# A necessary condition is that both the numerator and denominator 

# be perfect powers, which can be faster to disprove than the full 

# product (especially if both have a large prime factor). 

if mpz_cmpabs(mpq_numref(self.value), mpq_denref(self.value)) < 0: 

if not mpz_perfect_power_p(mpq_numref(self.value)): 

return False 

else: 

if not mpz_perfect_power_p(mpq_denref(self.value)): 

return False 

mpz_init(prod) 

mpz_mul(prod, mpq_numref(self.value), mpq_denref(self.value)) 

res = mpz_perfect_power_p(prod) 

mpz_clear(prod) 

return res == 1 

  

else: # self is negative 

  

if (mpz_cmp_ui(mpq_denref(self.value), 1) == 0): 

if (mpz_cmp_si(mpq_numref(self.value), -1) == 0): 

return True 

mpz_init(prod) 

mpz_mul_si(prod, mpq_numref(self.value), -1) 

while mpz_perfect_square_p(prod): 

mpz_sqrt(prod, prod) 

s = mpz_perfect_power_p(prod) 

mpz_clear(prod) 

return s == 1 

  

if not expected_value: 

if mpz_cmpabs(mpq_numref(self.value), mpq_denref(self.value)) < 0: 

mpz_init(prod) 

mpz_mul_si(prod, mpq_numref(self.value), -1) 

if mpz_cmp_ui(prod, 1) != 0: 

while mpz_perfect_square_p(prod): 

mpz_sqrt(prod, prod) 

if not mpz_perfect_power_p(prod): 

mpz_clear(prod) 

return False 

else: 

if not mpz_perfect_power_p(mpq_denref(self.value)): 

return False 

mpz_init(prod) 

else: 

mpz_init(prod) 

  

mpz_mul(prod, mpq_numref(self.value), mpq_denref(self.value)) 

mpz_mul_si(prod, prod, -1) 

while mpz_perfect_square_p(prod): 

mpz_sqrt(prod, prod) 

res = mpz_perfect_power_p(prod) 

mpz_clear(prod) 

return res == 1 

  

def squarefree_part(self): 

""" 

Return the square free part of `x`, i.e., an integer z such 

that `x = z y^2`, for a perfect square `y^2`. 

  

EXAMPLES:: 

  

sage: a = 1/2 

sage: a.squarefree_part() 

2 

sage: b = a/a.squarefree_part() 

sage: b, b.is_square() 

(1/4, True) 

sage: a = 24/5 

sage: a.squarefree_part() 

30 

""" 

return self.numer().squarefree_part() * self.denom().squarefree_part() 

  

def is_padic_square(self, p): 

""" 

Determines whether this rational number is a square in `\QQ_p` (or in 

`R` when ``p = infinity``). 

  

INPUT: 

  

- ``p`` - a prime number, or ``infinity`` 

  

EXAMPLES:: 

  

sage: QQ(2).is_padic_square(7) 

True 

sage: QQ(98).is_padic_square(7) 

True 

sage: QQ(2).is_padic_square(5) 

False 

  

TESTS:: 

  

sage: QQ(5/7).is_padic_square(int(2)) 

False 

""" 

## Special case when self is zero 

if self.is_zero(): 

return True 

  

## Deal with p = infinity (i.e. the real numbers) 

import sage.rings.infinity 

if p == sage.rings.infinity.infinity: 

return (self > 0) 

  

## Check that p is prime 

from .integer_ring import ZZ 

p = ZZ(p) 

if not p.is_prime(): 

raise ValueError('p must be "infinity" or a positive prime number.') 

  

## Deal with finite primes 

e, m = self.val_unit(p) 

  

if e % 2 == 1: 

return False 

  

if p == 2: 

return ((m % 8) == 1) 

  

from sage.arith.all import kronecker_symbol 

return (kronecker_symbol(m, p) == 1) 

  

def val_unit(self, p): 

r""" 

Returns a pair: the `p`-adic valuation of ``self``, and the `p`-adic 

unit of ``self``, as a :class:`Rational`. 

  

We do not require the `p` be prime, but it must be at least 2. For 

more documentation see :meth:`Integer.val_unit()`. 

  

INPUT: 

  

- ``p`` - a prime 

  

OUTPUT: 

  

- ``int`` - the `p`-adic valuation of this rational 

  

- ``Rational`` - `p`-adic unit part of ``self`` 

  

EXAMPLES:: 

  

sage: (-4/17).val_unit(2) 

(2, -1/17) 

sage: (-4/17).val_unit(17) 

(-1, -4) 

sage: (0/1).val_unit(17) 

(+Infinity, 1) 

  

AUTHORS: 

  

- David Roe (2007-04-12) 

""" 

return self._val_unit(p) 

  

# TODO -- change to use cpdef? If so, must fix 

# code in padics, etc. Do search_src('_val_unit'). 

cdef _val_unit(Rational self, integer.Integer p): 

""" 

This is called by :meth:`val_unit()`. 

  

EXAMPLES:: 

  

sage: (-4/17).val_unit(2) # indirect doctest 

(2, -1/17) 

""" 

cdef Rational u 

if mpz_cmp_ui(p.value, 2) < 0: 

raise ValueError("p must be at least 2.") 

if mpq_sgn(self.value) == 0: 

import sage.rings.infinity 

u = Rational.__new__(Rational) 

mpq_set_ui(u.value, 1, 1) 

return (sage.rings.infinity.infinity, u) 

cdef Integer v = Integer.__new__(Integer) 

u = Rational.__new__(Rational) 

sig_on() 

mpz_set_ui(v.value, mpz_remove(mpq_numref(u.value), mpq_numref(self.value), p.value)) 

sig_off() 

if mpz_sgn(v.value) != 0: 

mpz_set(mpq_denref(u.value), mpq_denref(self.value)) 

else: 

sig_on() 

mpz_set_ui(v.value, mpz_remove(mpq_denref(u.value), mpq_denref(self.value), p.value)) 

sig_off() 

mpz_neg(v.value, v.value) 

return (v, u) 

  

def prime_to_S_part(self, S=[]): 

r""" 

Returns ``self`` with all powers of all primes in ``S`` removed. 

  

INPUT: 

  

- ``S`` - list or tuple of primes. 

  

OUTPUT: rational 

  

.. NOTE:: 

  

Primality of the entries in `S` is not checked. 

  

EXAMPLES:: 

  

sage: QQ(3/4).prime_to_S_part() 

3/4 

sage: QQ(3/4).prime_to_S_part([2]) 

3 

sage: QQ(-3/4).prime_to_S_part([3]) 

-1/4 

sage: QQ(700/99).prime_to_S_part([2,3,5]) 

7/11 

sage: QQ(-700/99).prime_to_S_part([2,3,5]) 

-7/11 

sage: QQ(0).prime_to_S_part([2,3,5]) 

0 

sage: QQ(-700/99).prime_to_S_part([]) 

-700/99 

  

""" 

if self.is_zero(): 

return self 

a = self 

for p in S: 

e, a = a.val_unit(p) 

return a 

  

def sqrt(self, prec=None, extend=True, all=False): 

r""" 

The square root function. 

  

INPUT: 

  

- ``prec`` -- integer (default: ``None``): if ``None``, returns 

an exact square root; otherwise returns a numerical square root if 

necessary, to the given bits of precision. 

  

- ``extend`` -- bool (default: ``True``); if ``True``, return a 

square root in an extension ring, if necessary. Otherwise, raise a 

``ValueError`` if the square is not in the base ring. 

  

- ``all`` -- bool (default: ``False``); if ``True``, return all 

square roots of self, instead of just one. 

  

EXAMPLES:: 

  

sage: x = 25/9 

sage: x.sqrt() 

5/3 

sage: sqrt(x) 

5/3 

sage: x = 64/4 

sage: x.sqrt() 

4 

sage: x = 100/1 

sage: x.sqrt() 

10 

sage: x.sqrt(all=True) 

[10, -10] 

sage: x = 81/5 

sage: x.sqrt() 

9*sqrt(1/5) 

sage: x = -81/3 

sage: x.sqrt() 

3*sqrt(-3) 

  

:: 

  

sage: n = 2/3 

sage: n.sqrt() 

sqrt(2/3) 

sage: n.sqrt(prec=10) 

0.82 

sage: n.sqrt(prec=100) 

0.81649658092772603273242802490 

sage: n.sqrt(prec=100)^2 

0.66666666666666666666666666667 

sage: n.sqrt(prec=53, all=True) 

[0.816496580927726, -0.816496580927726] 

sage: n.sqrt(extend=False, all=True) 

Traceback (most recent call last): 

... 

ValueError: square root of 2/3 not a rational number 

sage: sqrt(-2/3, all=True) 

[sqrt(-2/3), -sqrt(-2/3)] 

sage: sqrt(-2/3, prec=53) 

0.816496580927726*I 

sage: sqrt(-2/3, prec=53, all=True) 

[0.816496580927726*I, -0.816496580927726*I] 

  

AUTHORS: 

  

- Naqi Jaffery (2006-03-05): some examples 

""" 

if mpq_sgn(self.value) == 0: 

return [self] if all else self 

  

if mpq_sgn(self.value) < 0: 

if not extend: 

raise ValueError("square root of negative number not rational") 

from sage.functions.other import _do_sqrt 

return _do_sqrt(self, prec=prec, all=all) 

  

cdef Rational z = <Rational> Rational.__new__(Rational) 

cdef mpz_t tmp 

cdef int non_square = 0 

  

sig_on() 

mpz_init(tmp) 

mpz_sqrtrem(mpq_numref(z.value), tmp, mpq_numref(self.value)) 

if mpz_sgn(tmp) != 0: 

non_square = 1 

else: 

mpz_sqrtrem(mpq_denref(z.value), tmp, mpq_denref(self.value)) 

if mpz_sgn(tmp) != 0: 

non_square = 1 

mpz_clear(tmp) 

sig_off() 

  

if non_square: 

if not extend: 

raise ValueError("square root of %s not a rational number" % self) 

from sage.functions.other import _do_sqrt 

return _do_sqrt(self, prec=prec, all=all) 

  

if prec: 

from sage.functions.other import _do_sqrt 

return _do_sqrt(self, prec=prec, all=all) 

  

if all: 

return [z, -z] 

return z 

  

def period(self): 

r""" 

Return the period of the repeating part of the decimal expansion of 

this rational number. 

  

ALGORITHM: 

  

When a rational number `n/d` with `(n,d)=1` is 

expanded, the period begins after `s` terms and has length 

`t`, where `s` and `t` are the smallest numbers satisfying 

`10^s=10^{s+t} \mod d`. In general if `d=2^a 5^b m` where `m` 

is coprime to 10, then `s=\max(a,b)` and `t` is the order of 

10 modulo `d`. 

  

EXAMPLES:: 

  

sage: (1/7).period() 

6 

sage: RR(1/7) 

0.142857142857143 

sage: (1/8).period() 

1 

sage: RR(1/8) 

0.125000000000000 

sage: RR(1/6) 

0.166666666666667 

sage: (1/6).period() 

1 

sage: x = 333/106 

sage: x.period() 

13 

sage: RealField(200)(x) 

3.1415094339622641509433962264150943396226415094339622641509 

""" 

cdef unsigned int alpha, beta 

d = self.denominator() 

alpha, d = d.val_unit(2) 

beta, d = d.val_unit(5) 

from sage.rings.finite_rings.integer_mod import Mod 

return Mod(10, d).multiplicative_order() 

  

def nth_root(self, int n): 

r""" 

Computes the `n`-th root of ``self``, or raises a 

``ValueError`` if ``self`` is not a perfect `n`-th power. 

  

INPUT: 

  

- ``n`` - integer (must fit in C int type) 

  

AUTHORS: 

  

- David Harvey (2006-09-15) 

  

EXAMPLES:: 

  

sage: (25/4).nth_root(2) 

5/2 

sage: (125/8).nth_root(3) 

5/2 

sage: (-125/8).nth_root(3) 

-5/2 

sage: (25/4).nth_root(-2) 

2/5 

  

:: 

  

sage: (9/2).nth_root(2) 

Traceback (most recent call last): 

... 

ValueError: not a perfect 2nd power 

  

:: 

  

sage: (-25/4).nth_root(2) 

Traceback (most recent call last): 

... 

ValueError: cannot take even root of negative number 

""" 

# TODO -- this could be quicker, by using GMP directly. 

cdef integer.Integer num 

cdef integer.Integer den 

cdef int negative 

  

if n > 0: 

negative = 0 

elif n < 0: 

n = -n 

negative = 1 

else: 

raise ValueError("n cannot be zero") 

  

num, exact = self.numerator().nth_root(n, 1) 

if not exact: 

raise ValueError("not a perfect %s power" % ZZ(n).ordinal_str()) 

  

den, exact = self.denominator().nth_root(n, 1) 

if not exact: 

raise ValueError("not a perfect %s power" % ZZ(n).ordinal_str()) 

  

if negative: 

return den / num 

else: 

return num / den 

  

def is_nth_power(self, int n): 

r""" 

Returns ``True`` if self is an `n`-th power, else ``False``. 

  

INPUT: 

  

- ``n`` - integer (must fit in C int type) 

  

.. NOTE:: 

  

Use this function when you need to test if a rational 

number is an `n`-th power, but do not need to know the value 

of its `n`-th root. If the value is needed, use :meth:`nth_root()`. 

  

AUTHORS: 

  

- John Cremona (2009-04-04) 

  

EXAMPLES:: 

  

sage: QQ(25/4).is_nth_power(2) 

True 

sage: QQ(125/8).is_nth_power(3) 

True 

sage: QQ(-125/8).is_nth_power(3) 

True 

sage: QQ(25/4).is_nth_power(-2) 

True 

  

sage: QQ(9/2).is_nth_power(2) 

False 

sage: QQ(-25).is_nth_power(2) 

False 

  

""" 

if n == 0: 

raise ValueError("n cannot be zero") 

if n<0: 

n = -n 

if n%2==0 and self<0: 

return False 

return self.numerator().nth_root(n, 1)[1]\ 

and self.denominator().nth_root(n, 1)[1] 

  

def str(self, int base=10): 

""" 

Return a string representation of ``self`` in the given ``base``. 

  

INPUT: 

  

- ``base`` -- integer (default: 10); base must be between 2 and 36. 

  

OUTPUT: string 

  

EXAMPLES:: 

  

sage: (-4/17).str() 

'-4/17' 

sage: (-4/17).str(2) 

'-100/10001' 

  

Note that the base must be at most 36. 

  

:: 

  

sage: (-4/17).str(40) 

Traceback (most recent call last): 

... 

ValueError: base (=40) must be between 2 and 36 

sage: (-4/17).str(1) 

Traceback (most recent call last): 

... 

ValueError: base (=1) must be between 2 and 36 

""" 

if base < 2 or base > 36: 

raise ValueError("base (=%s) must be between 2 and 36" % base) 

cdef size_t n 

cdef char *s 

  

n = mpz_sizeinbase (mpq_numref(self.value), base) \ 

+ mpz_sizeinbase (mpq_denref(self.value), base) + 3 

s = <char *>PyMem_Malloc(n) 

if s == NULL: 

raise MemoryError("Unable to allocate enough memory for the string representation of an integer.") 

  

sig_on() 

mpq_get_str(s, base, self.value) 

sig_off() 

k = char_to_str(s) 

PyMem_Free(s) 

return k 

  

def __float__(self): 

""" 

Return floating point approximation to ``self`` as a Python float. 

  

OUTPUT: float 

  

EXAMPLES:: 

  

sage: (-4/17).__float__() 

-0.23529411764705882 

sage: float(-4/17) 

-0.23529411764705882 

sage: float(1/3) 

0.3333333333333333 

sage: float(1/10) 

0.1 

sage: n = QQ(902834098234908209348209834092834098); float(n) 

9.028340982349083e+35 

  

TESTS: 

  

Test that conversion agrees with `RR`:: 

  

sage: Q = [a/b for a in [-99..99] for b in [1..99]] 

sage: all([RDF(q) == RR(q) for q in Q]) 

True 

  

Test that the conversion has correct rounding on simple rationals:: 

  

sage: for p in [-100..100]: 

....: for q in [1..100]: 

....: r = RDF(p/q) 

....: assert (RR(r).exact_rational() - p/q) <= r.ulp()/2 

  

Test larger rationals:: 

  

sage: Q = continued_fraction(pi).convergents()[:100] 

sage: all([RDF(q) == RR(q) for q in Q]) 

True 

  

At some point, the continued fraction and direct conversion 

to ``RDF`` should agree:: 

  

sage: RDFpi = RDF(pi) 

sage: all([RDF(q) == RDFpi for q in Q[20:]]) 

True 

""" 

return mpq_get_d_nearest(self.value) 

  

def __hash__(self): 

""" 

Return hash of ``self``. 

  

OUTPUT: integer 

  

EXAMPLES:: 

  

sage: QQ(42).__hash__() 

42 

sage: QQ(1/42).__hash__() 

1488680910 # 32-bit 

-7658195599476688946 # 64-bit 

sage: n = ZZ.random_element(10^100) 

sage: hash(n) == hash(QQ(n)) or n 

True 

sage: hash(-n) == hash(-QQ(n)) or n 

True 

sage: hash(-4/17) 

-47583156 # 32-bit 

8709371129873690700 # 64-bit 

""" 

cdef Py_hash_t n = mpz_pythonhash(mpq_numref(self.value)) 

cdef Py_hash_t d = mpz_pythonhash(mpq_denref(self.value)) 

# The constant below is (1 + sqrt(5)) << 61 

return n + (d - 1) * <Py_hash_t>(7461864723258187525) 

  

def __getitem__(self, int n): 

""" 

Return ``n``-th element of ``self``, viewed as a list. This is for 

consistency with how number field elements work. 

  

INPUT: 

  

- ``n`` - an integer (error if not 0 or -1) 

  

OUTPUT: Rational 

  

EXAMPLES:: 

  

sage: (-4/17)[0] 

-4/17 

sage: (-4/17)[1] 

Traceback (most recent call last): 

... 

IndexError: index n (=1) out of range; it must be 0 

sage: (-4/17)[-1] # indexing from the right 

-4/17 

""" 

if n == 0 or n == -1: 

return self 

raise IndexError("index n (=%s) out of range; it must be 0" % n) 

  

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

# Optimized arithmetic 

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

def __add__(left, right): 

""" 

Return ``left`` plus ``right`` 

  

EXAMPLES:: 

  

sage: (2/3) + (1/6) 

5/6 

sage: (1/3) + (1/2) 

5/6 

sage: (1/3) + 2 

7/3 

""" 

cdef Rational x 

if type(left) is type(right): 

x = <Rational> Rational.__new__(Rational) 

mpq_add(x.value, (<Rational>left).value, (<Rational>right).value) 

return x 

elif type(right) is Integer: 

x = <Rational> Rational.__new__(Rational) 

mpq_add_z(x.value, (<Rational>left).value, (<Integer>right).value) 

return x 

  

return coercion_model.bin_op(left, right, operator.add) 

  

cpdef _add_(self, right): 

""" 

Return ``right`` plus ``self``. 

  

EXAMPLES:: 

  

sage: (2/3)._add_(1/6) 

5/6 

sage: (1/3)._add_(1/2) 

5/6 

""" 

cdef Rational x 

x = <Rational> Rational.__new__(Rational) 

mpq_add(x.value, self.value, (<Rational>right).value) 

return x 

  

def __sub__(left, right): 

""" 

Return ``left`` minus ``right`` 

  

EXAMPLES:: 

  

sage: 11/3 - 5/4 

29/12 

  

sage: (2/3) - 2 

-4/3 

sage: (-2/3) - 1 

-5/3 

sage: (2/3) - (-3) 

11/3 

sage: (-2/3) - (-3) 

7/3 

sage: 2/3 - polygen(QQ) 

-x + 2/3 

""" 

cdef Rational x 

if type(left) is type(right): 

x = <Rational> Rational.__new__(Rational) 

mpq_sub(x.value, (<Rational>left).value, (<Rational>right).value) 

return x 

elif type(right) is Integer: 

x = <Rational> Rational.__new__(Rational) 

mpz_mul(mpq_numref(x.value), mpq_denref((<Rational>left).value), 

(<Integer>right).value) 

mpz_sub(mpq_numref(x.value), mpq_numref((<Rational>left).value), 

mpq_numref(x.value)) 

mpz_set(mpq_denref(x.value), mpq_denref((<Rational>left).value)) 

return x 

  

return coercion_model.bin_op(left, right, operator.sub) 

  

cpdef _sub_(self, right): 

""" 

Return ``self`` minus ``right``. 

  

EXAMPLES:: 

  

sage: (2/3)._sub_(1/6) 

1/2 

""" 

cdef Rational x 

x = <Rational> Rational.__new__(Rational) 

mpq_sub(x.value, self.value, (<Rational>right).value) 

return x 

  

cpdef _neg_(self): 

""" 

Negate ``self``. 

  

EXAMPLES:: 

  

sage: -(2/3) # indirect doctest 

-2/3 

""" 

cdef Rational x 

x = <Rational> Rational.__new__(Rational) 

mpq_neg(x.value, self.value) 

return x 

  

def __mul__(left, right): 

""" 

Return ``left`` times ``right``. 

  

EXAMPLES:: 

  

sage: (3/14) * 2/3 

1/7 

sage: (3/14) * 10 

15/7 

sage: 3/14 * polygen(QQ) 

3/14*x 

""" 

cdef Rational x 

if type(left) is type(right): 

x = <Rational> Rational.__new__(Rational) 

mpq_mul(x.value, (<Rational>left).value, (<Rational>right).value) 

return x 

elif type(right) is Integer: 

x = <Rational> Rational.__new__(Rational) 

mpq_mul_z(x.value, (<Rational>left).value, (<Integer>right).value) 

return x 

  

return coercion_model.bin_op(left, right, operator.mul) 

  

cpdef _mul_(self, right): 

""" 

Return ``self`` times ``right``. 

  

EXAMPLES:: 

  

sage: (3/14)._mul_(2/3) 

1/7 

""" 

cdef Rational x 

x = <Rational> Rational.__new__(Rational) 

if mpz_sizeinbase (mpq_numref(self.value), 2) > 100000 or \ 

mpz_sizeinbase (mpq_denref(self.value), 2) > 100000: 

# We only use the signal handler (to enable ctrl-c out) in case 

# self is huge, so the product might actually take a while to compute. 

sig_on() 

mpq_mul(x.value, self.value, (<Rational>right).value) 

sig_off() 

else: 

mpq_mul(x.value, self.value, (<Rational>right).value) 

return x 

  

def __div__(left, right): 

""" 

Return ``left`` divided by ``right`` 

  

EXAMPLES:: 

  

sage: QQ((2,3)) / QQ((-5,4)) 

-8/15 

sage: QQ((22,3)) / 4 

11/6 

sage: QQ((-2,3)) / (-4) 

1/6 

sage: QQ((2,3)) / QQ.zero() 

Traceback (most recent call last): 

... 

ZeroDivisionError: rational division by zero 

""" 

cdef Rational x 

if type(left) is type(right): 

if mpq_cmp_si((<Rational> right).value, 0, 1) == 0: 

raise ZeroDivisionError('rational division by zero') 

x = <Rational> Rational.__new__(Rational) 

mpq_div(x.value, (<Rational>left).value, (<Rational>right).value) 

return x 

elif type(right) is Integer: 

if mpz_cmp_si((<Integer> right).value, 0) == 0: 

raise ZeroDivisionError('rational division by zero') 

x = <Rational> Rational.__new__(Rational) 

mpq_div_zz(x.value, mpq_numref((<Rational>left).value), (<Integer>right).value) 

mpz_mul(mpq_denref(x.value), mpq_denref(x.value), 

mpq_denref((<Rational>left).value)) 

return x 

  

return coercion_model.bin_op(left, right, operator.div) 

  

cpdef _div_(self, right): 

""" 

Return ``self`` divided by ``right``. 

  

EXAMPLES:: 

  

sage: 2/3 # indirect doctest 

2/3 

sage: 3/0 # indirect doctest 

Traceback (most recent call last): 

... 

ZeroDivisionError: rational division by zero 

""" 

if mpq_cmp_si((<Rational> right).value, 0, 1) == 0: 

raise ZeroDivisionError('rational division by zero') 

cdef Rational x 

x = <Rational> Rational.__new__(Rational) 

mpq_div(x.value, self.value, (<Rational>right).value) 

return x 

  

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

# Other arithmetic operations. 

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

  

def __invert__(self): 

""" 

Return the multiplicative inverse of ``self``. 

  

OUTPUT: Rational 

  

EXAMPLES:: 

  

sage: (-4/17).__invert__() 

-17/4 

sage: ~(-4/17) 

-17/4 

""" 

if self.is_zero(): 

raise ZeroDivisionError('rational division by zero') 

cdef Rational x 

x = <Rational> Rational.__new__(Rational) 

mpq_inv(x.value, self.value) 

return x 

  

def __pow__(self, n, dummy): 

""" 

Raise ``self`` to the integer power ``n``. 

  

EXAMPLES:: 

  

sage: (2/3)^5 

32/243 

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

(-1)^(1/3) 

  

We raise to some interesting powers:: 

  

sage: (2/3)^I 

(2/3)^I 

sage: (2/3)^sqrt(2) 

(2/3)^sqrt(2) 

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

sage: (2/3)^(x^n + y^n + z^n) 

(2/3)^(x^n + y^n + z^n) 

sage: (-7/11)^(tan(x)+exp(x)) 

(-7/11)^(e^x + tan(x)) 

sage: (2/3)^(3/4) 

(2/3)^(3/4) 

sage: (-1/3)^0 

1 

sage: a = (0/1)^(0/1); a 

1 

sage: type(a) 

<type 'sage.rings.rational.Rational'> 

  

The exponent must fit in a long unless the base is -1, 0, or 1. 

  

:: 

  

sage: s = (1/2)^(2^100) 

Traceback (most recent call last): 

... 

RuntimeError: exponent must be at most 2147483647 # 32-bit 

RuntimeError: exponent must be at most 9223372036854775807 # 64-bit 

sage: s = (1/2)^(-2^100) 

Traceback (most recent call last): 

... 

RuntimeError: exponent must be at most 2147483647 # 32-bit 

RuntimeError: exponent must be at most 9223372036854775807 # 64-bit 

sage: (-3/3)^(2^100) 

1 

  

This works even if the base is a float or Python complex or other 

type:: 

  

sage: float(1.2)**(1/2) 

1.0954451150103321 

sage: complex(1,2)**(1/2) 

(1.272019649514069+0.786151377757423...j) 

sage: int(2)^(1/2) 

sqrt(2) 

sage: a = int(2)^(3/1); a 

8 

sage: type(a) 

<type 'sage.rings.rational.Rational'> 

  

If the result is rational, it is returned as a rational:: 

  

sage: (4/9)^(1/2) 

2/3 

sage: parent((4/9)^(1/2)) 

Rational Field 

sage: (-27/125)^(1/3) 

3/5*(-1)^(1/3) 

sage: (-27/125)^(1/2) 

3/5*sqrt(-3/5) 

  

The result is normalized to have the rational power in the numerator:: 

  

sage: 2^(-1/2) 

1/2*sqrt(2) 

sage: 8^(-1/5) 

1/8*8^(4/5) 

sage: 3^(-3/2) 

1/9*sqrt(3) 

  

TESTS:: 

  

sage: QQ(0)^(-1) 

Traceback (most recent call last): 

... 

ZeroDivisionError: rational division by zero 

""" 

if dummy is not None: 

raise ValueError("__pow__ dummy variable not used") 

  

if not isinstance(self, Rational): 

# If the base is not a rational, e.g., it is an int, complex, float, user-defined type, etc. 

try: 

self_coerced = n.parent().coerce(self) 

except TypeError: 

n_coerced = type(self)(n) 

if n != n_coerced: 

# dangerous coercion -- don't use -- try symbolic result 

from sage.calculus.calculus import SR 

return SR(self)**SR(n) 

return self ** n_coerced 

return self_coerced ** n 

  

cdef Rational _self = <Rational>self 

cdef long nn 

  

try: 

nn = pyobject_to_long(n) 

except TypeError: 

if isinstance(n, Rational): 

# Perhaps it can be done exactly 

c, d = rational_power_parts(self, n) 

if d == 1: 

# It was an exact power 

return c 

elif d == -1 and n.denominator() == 2: 

from sage.symbolic.all import I 

return c * I.pyobject() ** (n.numerator() % 4) 

elif c != 1: 

return c * d**n 

# Can't simplify the power, return a symbolic expression. 

# We use the hold=True keyword argument to prevent the 

# symbolics library from trying to simplify this expression 

# again. This would lead to infinite loops otherwise. 

from sage.symbolic.ring import SR 

if n < 0: 

int_exp = -(n.floor()) 

return SR(1/self**int_exp)*\ 

SR(self).power(int_exp+n, hold=True) 

else: 

return SR(self).power(n, hold=True) 

  

if isinstance(n, Element): 

return (<Element>n)._parent(self)**n 

try: 

return n.parent()(self)**n 

except AttributeError: 

try: 

return type(n)(self)**n 

except Exception: 

raise TypeError("exponent (=%s) must be an integer.\nCoerce your numbers to real or complex numbers first." % n) 

  

except OverflowError: 

if mpz_cmp_si(mpq_denref(_self.value), 1) == 0: 

if mpz_cmp_si(mpq_numref(_self.value), 1) == 0: 

return self 

elif mpz_cmp_si(mpq_numref(_self.value), 0) == 0: 

return self 

elif mpz_cmp_si(mpq_numref(_self.value), -1) == 0: 

return self if n % 2 else -self 

raise RuntimeError("exponent must be at most %s" % sys.maxsize) 

  

cdef Rational x = <Rational> Rational.__new__(Rational) 

  

if nn == 0: 

mpq_set_si(x.value, 1, 1) 

return x 

  

if nn < 0: 

if mpz_sgn(mpq_numref(_self.value)) == 0: 

raise ZeroDivisionError('rational division by zero') 

  

sig_on() 

# mpz_pow_ui(mpq_denref(x.value), mpq_numref(_self.value), <unsigned long int>(-nn)) 

# mpz_pow_ui(mpq_numref(x.value), mpq_denref(_self.value), <unsigned long int>(-nn)) 

# The above causes segfaults, so swap after instead... 

mpz_pow_ui(mpq_numref(x.value), mpq_numref(_self.value), -nn) 

mpz_pow_ui(mpq_denref(x.value), mpq_denref(_self.value), -nn) 

# mpz_swap(mpq_numref(x.value), mpq_denref(x.value)) # still a segfault 

mpq_inv(x.value, x.value) 

sig_off() 

return x 

elif nn > 0: 

sig_on() 

mpz_pow_ui(mpq_numref(x.value), mpq_numref(_self.value), nn) 

mpz_pow_ui(mpq_denref(x.value), mpq_denref(_self.value), nn) 

sig_off() 

return x 

  

  

if n < 0: # this doesn't make sense unless n is an integer. 

x = _self**(-n) 

return ~x 

  

cdef mpz_t num, den 

  

sig_on() 

mpz_init(num) 

mpz_init(den) 

mpz_pow_ui(num, mpq_numref(_self.value), nn) 

mpz_pow_ui(den, mpq_denref(_self.value), nn) 

mpq_set_num(x.value, num) 

mpq_set_den(x.value, den) 

mpz_clear(num) 

mpz_clear(den) 

sig_off() 

  

return x 

  

def __pos__(self): 

""" 

Return ``self``. 

  

OUTPUT: Rational 

  

EXAMPLES:: 

  

sage: (-4/17).__pos__() 

-4/17 

sage: +(-4/17) 

-4/17 

""" 

return self 

  

def __neg__(self): 

""" 

Return the negative of ``self``. 

  

OUTPUT: Rational 

  

EXAMPLES:: 

  

sage: (-4/17).__neg__() 

4/17 

sage: - (-4/17) 

4/17 

""" 

cdef Rational x 

x = <Rational> Rational.__new__(Rational) 

mpq_neg(x.value, self.value) 

return x 

  

def __nonzero__(self): 

""" 

Return ``True`` if this rational number is nonzero. 

  

OUTPUT: bool 

  

EXAMPLES:: 

  

sage: bool(0/5) 

False 

sage: bool(-4/17) 

True 

""" 

# A rational number is zero iff its numerator is zero. 

return mpq_sgn(self.value) != 0 

  

def __abs__(self): 

""" 

Return the absolute value of this rational number. 

  

OUTPUT: Rational 

  

EXAMPLES:: 

  

sage: (-4/17).__abs__() 

4/17 

sage: abs(-4/17) 

4/17 

""" 

cdef Rational x 

x = <Rational> Rational.__new__(Rational) 

mpq_abs(x.value, self.value) 

return x 

  

def sign(self): 

""" 

Returns the sign of this rational number, which is -1, 0, or 1 

depending on whether this number is negative, zero, or positive 

respectively. 

  

OUTPUT: Integer 

  

EXAMPLES:: 

  

sage: (2/3).sign() 

1 

sage: (0/3).sign() 

0 

sage: (-1/6).sign() 

-1 

""" 

return integer.smallInteger(mpq_sgn(self.value)) 

  

def mod_ui(Rational self, unsigned long int n): 

""" 

Return the remainder upon division of ``self`` by the unsigned long 

integer ``n``. 

  

INPUT: 

  

- ``n`` - an unsigned long integer 

  

OUTPUT: integer 

  

EXAMPLES:: 

  

sage: (-4/17).mod_ui(3) 

1 

sage: (-4/17).mod_ui(17) 

Traceback (most recent call last): 

... 

ArithmeticError: The inverse of 0 modulo 17 is not defined. 

""" 

cdef unsigned int num, den, a 

  

# Documentation from GMP manual: 

# "For the ui variants the return value is the remainder, and 

# in fact returning the remainder is all the div_ui functions do." 

sig_on() 

num = mpz_fdiv_ui(mpq_numref(self.value), n) 

den = mpz_fdiv_ui(mpq_denref(self.value), n) 

sig_off() 

return int((num * ai.inverse_mod_int(den, n)) % n) 

  

def __mod__(x, y): 

""" 

Return the remainder of division of ``x`` by ``y``, where ``y`` is 

something that can be coerced to an integer. 

  

INPUT: 

  

- ``other`` - object that coerces to an integer. 

  

OUTPUT: integer 

  

EXAMPLES:: 

  

sage: (-4/17).__mod__(3/1) 

1 

  

TESTS: 

  

Check that :trac:`14870` is fixed:: 

  

sage: int(4) % QQ(3) 

1 

""" 

cdef Rational rat 

if not isinstance(x, Rational): 

rat = Rational(x) 

else: 

rat = x 

cdef other = integer.Integer(y) 

if not other: 

raise ZeroDivisionError("Rational modulo by zero") 

n = rat.numer() % other 

d = rat.denom() % other 

d = d.inverse_mod(other) 

return (n * d) % other 

  

def norm(self): 

r""" 

Returns the norm from `\QQ` to `\QQ` of `x` (which is just `x`). This 

was added for compatibility with :class:`NumberFields`. 

  

OUTPUT: 

  

- ``Rational`` - reference to ``self`` 

  

EXAMPLES:: 

  

sage: (1/3).norm() 

1/3 

  

AUTHORS: 

  

- Craig Citro 

""" 

return self 

  

def relative_norm(self): 

""" 

Returns the norm from Q to Q of x (which is just x). This was added for compatibility with NumberFields 

  

EXAMPLES:: 

  

sage: (6/5).relative_norm() 

6/5 

  

sage: QQ(7/5).relative_norm() 

7/5 

""" 

return self 

  

def absolute_norm(self): 

""" 

Returns the norm from Q to Q of x (which is just x). This was added for compatibility with NumberFields 

  

EXAMPLES:: 

  

sage: (6/5).absolute_norm() 

6/5 

  

sage: QQ(7/5).absolute_norm() 

7/5 

""" 

return self 

  

def trace(self): 

r""" 

Returns the trace from `\QQ` to `\QQ` of `x` (which is just `x`). This 

was added for compatibility with :class:`NumberFields`. 

  

OUTPUT: 

  

- ``Rational`` - reference to self 

  

EXAMPLES:: 

  

sage: (1/3).trace() 

1/3 

  

AUTHORS: 

  

- Craig Citro 

""" 

return self 

  

def charpoly(self, var='x'): 

""" 

Return the characteristic polynomial of this rational number. This 

will always be just ``var - self``; this is really here so that code 

written for number fields won't crash when applied to rational 

numbers. 

  

INPUT: 

  

- ``var`` - a string 

  

OUTPUT: Polynomial 

  

EXAMPLES:: 

  

sage: (1/3).charpoly('x') 

x - 1/3 

  

The default is var='x'. (:trac:`20967`):: 

  

sage: a = QQ(2); a.charpoly('x') 

x - 2 

  

  

AUTHORS: 

  

- Craig Citro 

""" 

QQ = self.parent() 

return QQ[var]([-self,1]) 

  

def minpoly(self, var='x'): 

""" 

Return the minimal polynomial of this rational number. This will 

always be just ``x - self``; this is really here so that code written 

for number fields won't crash when applied to rational numbers. 

  

INPUT: 

  

- ``var`` - a string 

  

OUTPUT: Polynomial 

  

EXAMPLES:: 

  

sage: (1/3).minpoly() 

x - 1/3 

sage: (1/3).minpoly('y') 

y - 1/3 

  

AUTHORS: 

  

- Craig Citro 

""" 

QQ = self.parent() 

return QQ[var]([-self,1]) 

  

def _integer_(self, Z=None): 

""" 

Return ``self`` coerced to an integer. Of course this rational number 

must have a denominator of 1. 

  

OUTPUT: Integer 

  

EXAMPLES:: 

  

sage: (-4/17)._integer_() 

Traceback (most recent call last): 

... 

TypeError: no conversion of this rational to integer 

sage: (-4/1)._integer_() 

-4 

""" 

if not mpz_cmp_si(mpq_denref(self.value), 1) == 0: 

raise TypeError("no conversion of this rational to integer") 

cdef Integer n = Integer.__new__(Integer) 

n.set_from_mpz(mpq_numref(self.value)) 

return n 

  

def numerator(self): 

""" 

Return the numerator of this rational number. 

numer is an alias of numerator. 

  

EXAMPLES:: 

  

sage: x = 5/11 

sage: x.numerator() 

5 

  

sage: x = 9/3 

sage: x.numerator() 

3 

  

sage: x = -5/11 

sage: x.numer() 

-5 

""" 

cdef Integer n = Integer.__new__(Integer) 

n.set_from_mpz(mpq_numref(self.value)) 

return n 

  

#Define an alias for numerator 

numer = numerator 

  

IF PY_MAJOR_VERSION <= 2: 

def __int__(self): 

""" 

Convert this rational to a Python ``int``. 

  

This truncates ``self`` if ``self`` has a denominator (which is 

consistent with Python's ``long(floats)``). 

  

EXAMPLES:: 

  

sage: int(7/3) 

2 

sage: int(-7/3) 

-2 

""" 

return int(self.__long__()) 

  

def __long__(self): 

""" 

Convert this rational to a Python ``long`` (``int`` on Python 3). 

  

This truncates ``self`` if ``self`` has a denominator (which is 

consistent with Python's ``long(floats)``). 

  

EXAMPLES:: 

  

sage: long(7/3) 

2L 

sage: long(-7/3) 

-2L 

""" 

cdef mpz_t x 

if mpz_cmp_si(mpq_denref(self.value),1) != 0: 

mpz_init(x) 

mpz_tdiv_q(x, mpq_numref(self.value), mpq_denref(self.value)) 

n = mpz_get_pylong(x) 

mpz_clear(x) 

return n 

else: 

return mpz_get_pylong(mpq_numref(self.value)) 

  

def denominator(self): 

""" 

Returns the denominator of this rational number. 

denom is an alias of denominator. 

  

EXAMPLES:: 

  

sage: x = -5/11 

sage: x.denominator() 

11 

  

sage: x = 9/3 

sage: x.denominator() 

1 

  

sage: x = 5/13 

sage: x.denom() 

13 

""" 

cdef Integer n = Integer.__new__(Integer) 

n.set_from_mpz(mpq_denref(self.value)) 

return n 

  

#Define an alias for denominator 

denom = denominator 

  

def factor(self): 

""" 

Return the factorization of this rational number. 

  

OUTPUT: Factorization 

  

EXAMPLES:: 

  

sage: (-4/17).factor() 

-1 * 2^2 * 17^-1 

  

Trying to factor 0 gives an arithmetic error:: 

  

sage: (0/1).factor() 

Traceback (most recent call last): 

... 

ArithmeticError: factorization of 0 is not defined 

""" 

from sage.structure.factorization import Factorization 

return self.numerator().factor() * \ 

Factorization([(p, -e) for p, e in self.denominator().factor()]) 

  

def support(self): 

""" 

Return a sorted list of the primes where this rational number has 

non-zero valuation. 

  

OUTPUT: The set of primes appearing in the factorization of this 

rational with nonzero exponent, as a sorted list. 

  

EXAMPLES:: 

  

sage: (-4/17).support() 

[2, 17] 

  

Trying to find the support of 0 gives an arithmetic error:: 

  

sage: (0/1).support() 

Traceback (most recent call last): 

... 

ArithmeticError: Support of 0 not defined. 

""" 

if self.is_zero(): 

raise ArithmeticError("Support of 0 not defined.") 

return sage.arith.all.prime_factors(self) 

  

def log(self, m=None, prec=None): 

r""" 

Return the log of ``self``. 

  

INPUT: 

  

- ``m`` -- the base (default: natural log base e) 

  

- ``prec`` -- integer (optional); the precision in bits 

  

OUTPUT: 

  

When ``prec`` is not given, the log as an element in symbolic 

ring unless the logarithm is exact. Otherwise the log is a 

:class:`RealField` approximation to ``prec`` bit precision. 

  

EXAMPLES:: 

  

sage: (124/345).log(5) 

log(124/345)/log(5) 

sage: (124/345).log(5,100) 

-0.63578895682825611710391773754 

sage: log(QQ(125)) 

3*log(5) 

sage: log(QQ(125), 5) 

3 

sage: log(QQ(125), 3) 

3*log(5)/log(3) 

sage: QQ(8).log(1/2) 

-3 

sage: (1/8).log(1/2) 

3 

sage: (1/2).log(1/8) 

1/3 

sage: (1/2).log(8) 

-1/3 

sage: (16/81).log(8/27) 

4/3 

sage: (8/27).log(16/81) 

3/4 

sage: log(27/8, 16/81) 

-3/4 

sage: log(16/81, 27/8) 

-4/3 

sage: (125/8).log(5/2) 

3 

sage: (125/8).log(5/2,prec=53) 

3.00000000000000 

""" 

if self.denom() == ZZ.one(): 

return ZZ(self.numer()).log(m, prec) 

if mpz_sgn(mpq_numref(self.value)) < 0: 

from sage.symbolic.all import SR 

return SR(self).log() 

if m is not None and m <= 0: 

raise ValueError("log base must be positive") 

if prec: 

from sage.rings.real_mpfr import RealField 

if m is None: 

return RealField(prec)(self).log() 

return RealField(prec)(self).log(m) 

  

from sage.functions.log import function_log 

if m is None: 

return function_log(self, dont_call_method_on_arg=True) 

  

anum = self.numer() 

aden = self.denom() 

mrat = Rational(m) 

bnum = mrat.numer() 

bden = mrat.denom() 

  

anp = anum.perfect_power() 

bnp = bnum.perfect_power() 

adp = aden.perfect_power() 

bdp = bden.perfect_power() 

if (anp[0] == bnp[0] and adp[0] == bdp[0]): 

nu_ratio = Rational((anp[1], bnp[1])) 

de_ratio = Rational((adp[1], bdp[1])) 

if nu_ratio == de_ratio: 

return nu_ratio 

if nu_ratio == ZZ.one(): 

return de_ratio 

if de_ratio == ZZ.one(): 

return nu_ratio 

elif (anp[0] == bdp[0] and adp[0] == bnp[0]): 

up_ratio = Rational((anp[1], bdp[1])) 

lo_ratio = Rational((adp[1], bnp[1])) 

if up_ratio == lo_ratio: 

return -up_ratio 

if up_ratio == ZZ.one(): 

return -lo_ratio 

if lo_ratio == ZZ.one(): 

return -up_ratio 

  

return (function_log(self, dont_call_method_on_arg=True) / 

function_log(m, dont_call_method_on_arg=True)) 

  

def gamma(self, prec=None): 

""" 

Return the gamma function evaluated at ``self``. This value is exact 

for integers and half-integers, and returns a symbolic value 

otherwise. For a numerical approximation, use keyword ``prec``. 

  

EXAMPLES:: 

  

sage: gamma(1/2) 

sqrt(pi) 

sage: gamma(7/2) 

15/8*sqrt(pi) 

sage: gamma(-3/2) 

4/3*sqrt(pi) 

sage: gamma(6/1) 

120 

sage: gamma(1/3) 

gamma(1/3) 

  

This function accepts an optional precision argument:: 

  

sage: (1/3).gamma(prec=100) 

2.6789385347077476336556929410 

sage: (1/2).gamma(prec=100) 

1.7724538509055160272981674833 

""" 

if prec: 

return self.n(prec).gamma() 

else: 

if mpz_cmp_ui(mpq_denref(self.value), 1) == 0: 

return integer.Integer(self).gamma() 

elif mpz_cmp_ui(mpq_denref(self.value), 2) == 0: 

numer = self.numer() 

rat_part = Rational((numer-2).multifactorial(2)) >> ((numer-1)//2) 

from sage.symbolic.constants import pi 

from sage.functions.all import sqrt 

return sqrt(pi) * rat_part 

else: 

from sage.symbolic.all import SR 

return SR(self).gamma() 

  

def floor(self): 

""" 

Return the floor of this rational number as an integer. 

  

OUTPUT: Integer 

  

EXAMPLES:: 

  

sage: n = 5/3; n.floor() 

1 

sage: n = -17/19; n.floor() 

-1 

sage: n = -7/2; n.floor() 

-4 

sage: n = 7/2; n.floor() 

3 

sage: n = 10/2; n.floor() 

5 

""" 

cdef integer.Integer n 

n = integer.Integer() 

mpz_fdiv_q(n.value, mpq_numref(self.value), mpq_denref(self.value)) 

return n 

  

def ceil(self): 

""" 

Return the ceiling of this rational number. 

  

OUTPUT: Integer 

  

If this rational number is an integer, this returns this number, 

otherwise it returns the floor of this number +1. 

  

EXAMPLES:: 

  

sage: n = 5/3; n.ceil() 

2 

sage: n = -17/19; n.ceil() 

0 

sage: n = -7/2; n.ceil() 

-3 

sage: n = 7/2; n.ceil() 

4 

sage: n = 10/2; n.ceil() 

5 

""" 

cdef integer.Integer n 

n = integer.Integer() 

mpz_cdiv_q(n.value, mpq_numref(self.value), mpq_denref(self.value)) 

return n 

  

def trunc(self): 

""" 

Round this rational number to the nearest integer toward zero. 

  

EXAMPLES:: 

  

sage: (5/3).trunc() 

1 

sage: (-5/3).trunc() 

-1 

sage: QQ(42).trunc() 

42 

sage: QQ(-42).trunc() 

-42 

""" 

cdef integer.Integer n 

n = integer.Integer() 

mpz_tdiv_q(n.value, mpq_numref(self.value), mpq_denref(self.value)) 

return n 

  

def round(Rational self, mode="away"): 

""" 

Returns the nearest integer to ``self``, rounding away from 0 by 

default, for consistency with the builtin Python round. 

  

INPUT: 

  

- ``self`` - a rational number 

  

- ``mode`` - a rounding mode for half integers: 

  

- 'toward' rounds toward zero 

- 'away' (default) rounds away from zero 

- 'up' rounds up 

- 'down' rounds down 

- 'even' rounds toward the even integer 

- 'odd' rounds toward the odd integer 

  

  

OUTPUT: Integer 

  

EXAMPLES:: 

  

sage: (9/2).round() 

5 

sage: n = 4/3; n.round() 

1 

sage: n = -17/4; n.round() 

-4 

sage: n = -5/2; n.round() 

-3 

sage: n.round("away") 

-3 

sage: n.round("up") 

-2 

sage: n.round("down") 

-3 

sage: n.round("even") 

-2 

sage: n.round("odd") 

-3 

""" 

if not (mode in ['toward', 'away', 'up', 'down', 'even', 'odd']): 

raise ValueError("rounding mode must be one of 'toward', 'away', 'up', 'down', 'even', or 'odd'") 

if self.denominator() == 1: 

from sage.rings.integer import Integer 

return Integer(self) 

if self.denominator() == 2: 

# round down: 

if (mode == "down") or \ 

(mode == "toward" and self > 0) or \ 

(mode == "away" and self < 0) or \ 

(mode == "even" and self.numerator() % 4 == 1) or \ 

(mode == "odd" and self.numerator() % 4 == 3): 

return self.numerator() // self.denominator() 

else: 

return self.numerator() // self.denominator() + 1 

else: 

q, r = self.numerator().quo_rem(self.denominator()) 

if r < self.denominator() / 2: 

return q 

else: 

return q+1 

  

def real(self): 

""" 

Returns the real part of ``self``, which is ``self``. 

  

EXAMPLES:: 

  

sage: (1/2).real() 

1/2 

""" 

return self 

  

def imag(self): 

""" 

Returns the imaginary part of ``self``, which is zero. 

  

EXAMPLES:: 

  

sage: (1/239).imag() 

0 

""" 

return self._parent(0) 

  

def height(self): 

""" 

The max absolute value of the numerator and denominator of ``self``, as 

an :class:`Integer`. 

  

OUTPUT: Integer 

  

EXAMPLES:: 

  

sage: a = 2/3 

sage: a.height() 

3 

sage: a = 34/3 

sage: a.height() 

34 

sage: a = -97/4 

sage: a.height() 

97 

  

AUTHORS: 

  

- Naqi Jaffery (2006-03-05): examples 

  

.. NOTE:: 

  

For the logarithmic height, use :meth:`global_height()`. 

  

""" 

x = abs(self.numer()) 

if x > self.denom(): 

return x 

return self.denom() 

  

def _lcm(self, Rational other): 

""" 

Returns the least common multiple, in the rational numbers, of ``self`` 

and ``other``. This function returns either 0 or 1 (as a rational 

number). 

  

INPUT: 

  

- ``other`` - Rational 

  

OUTPUT: 

  

- ``Rational`` - 0 or 1 

  

EXAMPLES:: 

  

sage: (2/3)._lcm(3/5) 

1 

sage: (0/1)._lcm(0/1) 

0 

sage: type((2/3)._lcm(3/5)) 

<type 'sage.rings.rational.Rational'> 

""" 

if mpz_cmp_si(mpq_numref(self.value), 0) == 0 and \ 

mpz_cmp_si(mpq_numref(other.value), 0) == 0: 

return Rational(0) 

return Rational(1) 

  

def additive_order(self): 

""" 

Return the additive order of ``self``. 

  

OUTPUT: integer or infinity 

  

EXAMPLES:: 

  

sage: QQ(0).additive_order() 

1 

sage: QQ(1).additive_order() 

+Infinity 

""" 

import sage.rings.infinity 

if self.is_zero(): 

return integer.Integer(1) 

else: 

return sage.rings.infinity.infinity 

  

  

def multiplicative_order(self): 

""" 

Return the multiplicative order of ``self``. 

  

OUTPUT: Integer or ``infinity`` 

  

EXAMPLES:: 

  

sage: QQ(1).multiplicative_order() 

1 

sage: QQ('1/-1').multiplicative_order() 

2 

sage: QQ(0).multiplicative_order() 

+Infinity 

sage: QQ('2/3').multiplicative_order() 

+Infinity 

sage: QQ('1/2').multiplicative_order() 

+Infinity 

""" 

import sage.rings.infinity 

if self.is_one(): 

return integer.Integer(1) 

elif mpz_cmpabs(mpq_numref(self.value),mpq_denref(self.value))==0: 

# if the numerator and the denominator are equal in absolute value, 

# then the rational number is -1 

return integer.Integer(2) 

else: 

return sage.rings.infinity.infinity 

  

def is_one(self): 

r""" 

Determine if a rational number is one. 

  

OUTPUT: bool 

  

EXAMPLES:: 

  

sage: QQ(1/2).is_one() 

False 

sage: QQ(4/4).is_one() 

True 

""" 

# A rational number is equal to 1 iff its numerator and denominator are equal 

return mpz_cmp(mpq_numref(self.value),mpq_denref(self.value))==0 

  

def is_integral(self): 

r""" 

Determine if a rational number is integral (i.e is in 

`\ZZ`). 

  

OUTPUT: bool 

  

EXAMPLES:: 

  

sage: QQ(1/2).is_integral() 

False 

sage: QQ(4/4).is_integral() 

True 

""" 

return mpz_cmp_si(mpq_denref(self.value), 1) == 0 

  

def is_rational(self): 

r""" 

Return ``True`` since this is a rational number. 

  

EXAMPLES:: 

  

sage: (3/4).is_rational() 

True 

""" 

return True 

  

#Function alias for checking if the number is a integer.Added to solve ticket 15500  

is_integer = is_integral 

  

  

def is_S_integral(self, S=[]): 

r""" 

Determine if the rational number is ``S``-integral. 

  

``x`` is ``S``-integral if ``x.valuation(p)>=0`` for all ``p`` not in 

``S``, i.e., the denominator of ``x`` is divisible only by the primes 

in ``S``. 

  

INPUT: 

  

- ``S`` -- list or tuple of primes. 

  

OUTPUT: bool 

  

.. NOTE:: 

  

Primality of the entries in ``S`` is not checked. 

  

EXAMPLES:: 

  

sage: QQ(1/2).is_S_integral() 

False 

sage: QQ(1/2).is_S_integral([2]) 

True 

sage: [a for a in range(1,11) if QQ(101/a).is_S_integral([2,5])] 

[1, 2, 4, 5, 8, 10] 

""" 

if self.is_integral(): 

return True 

return self.prime_to_S_part(S).is_integral() 

  

def is_S_unit(self, S=None): 

r""" 

Determine if the rational number is an ``S``-unit. 

  

``x`` is an ``S``-unit if ``x.valuation(p)==0`` for all ``p`` not in 

``S``, i.e., the numerator and denominator of ``x`` are divisible only 

by the primes in `S`. 

  

INPUT: 

  

- ``S`` -- list or tuple of primes. 

  

OUTPUT: bool 

  

.. NOTE:: 

  

Primality of the entries in ``S`` is not checked. 

  

EXAMPLES:: 

  

sage: QQ(1/2).is_S_unit() 

False 

sage: QQ(1/2).is_S_unit([2]) 

True 

sage: [a for a in range(1,11) if QQ(10/a).is_S_unit([2,5])] 

[1, 2, 4, 5, 8, 10] 

""" 

a = self.abs() 

if a==1: 

return True 

if S is None: 

return False 

return a.prime_to_S_part(S) == 1 

  

cdef _lshift(self, long int exp): 

r""" 

Return ``self * 2^exp``. 

""" 

cdef Rational x 

x = <Rational> Rational.__new__(Rational) 

sig_on() 

if exp < 0: 

mpq_div_2exp(x.value,self.value,-exp) 

else: 

mpq_mul_2exp(x.value,self.value,exp) 

sig_off() 

return x 

  

def __lshift__(x,y): 

""" 

Left shift operator ``x << y``. 

  

INPUT: 

  

- ``x, y`` -- integer or rational 

  

OUTPUT: Rational 

  

EXAMPLES:: 

  

sage: (2/3).__lshift__(4/1) 

32/3 

sage: (2/3).__lshift__(4/7) 

Traceback (most recent call last): 

... 

ValueError: denominator must be 1 

sage: (2).__lshift__(4/1) 

32 

sage: (2/3).__lshift__(4) 

32/3 

sage: (2/3) << (4/1) 

32/3 

""" 

if isinstance(x, Rational): 

if isinstance(y, (int, long, integer.Integer)): 

return (<Rational>x)._lshift(y) 

if isinstance(y, Rational): 

if mpz_cmp_si(mpq_denref((<Rational>y).value), 1) != 0: 

raise ValueError("denominator must be 1") 

return (<Rational>x)._lshift(y) 

return bin_op(x, y, operator.lshift) 

  

cdef _rshift(self, long int exp): 

r""" 

Return ``self / 2^exp``. 

""" 

cdef Rational x 

x = <Rational> Rational.__new__(Rational) 

sig_on() 

if exp < 0: 

mpq_mul_2exp(x.value,self.value,-exp) 

else: 

mpq_div_2exp(x.value,self.value,exp) 

sig_off() 

return x 

  

def __rshift__(x,y): 

""" 

Right shift operator ``x >> y``. 

  

INPUT: 

  

- ``x, y`` -- integer or rational 

  

OUTPUT: Rational 

  

EXAMPLES:: 

  

sage: (2/3).__rshift__(4/1) 

1/24 

sage: (2/3).__rshift__(4/7) 

Traceback (most recent call last): 

... 

ValueError: denominator must be 1 

sage: (2).__rshift__(4/1) 

0 

sage: (2/1).__rshift__(4) 

1/8 

sage: (2/1) >>(4/1) 

1/8 

""" 

if isinstance(x, Rational): 

if isinstance(y, (int, long, integer.Integer)): 

return (<Rational>x)._rshift(y) 

if isinstance(y, Rational): 

if mpz_cmp_si(mpq_denref((<Rational>y).value), 1) != 0: 

raise ValueError("denominator must be 1") 

return (<Rational>x)._rshift(y) 

return bin_op(x, y, operator.rshift) 

  

def conjugate(self): 

""" 

Return the complex conjugate of this rational number, which is 

the number itself. 

  

EXAMPLES:: 

  

sage: n = 23/11 

sage: n.conjugate() 

23/11 

""" 

return self 

  

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

# Support for interfaces 

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

  

def __pari__(self): 

""" 

Returns the PARI version of this rational number. 

  

EXAMPLES:: 

  

sage: n = 9390823/17 

sage: m = n.__pari__(); m 

9390823/17 

sage: type(m) 

<type 'cypari2.gen.Gen'> 

sage: m.type() 

't_FRAC' 

""" 

return new_gen_from_mpq_t(self.value) 

  

def _interface_init_(self, I=None): 

""" 

Return representation of this rational suitable for coercing into 

almost any computer algebra system. 

  

OUTPUT: string 

  

EXAMPLES:: 

  

sage: (2/3)._interface_init_() 

'2/3' 

sage: kash(3/1).Type() # optional - kash 

elt-fld^rat 

sage: magma(3/1).Type() # optional - magma 

FldRatElt 

""" 

return '%s/%s'%(self.numerator(), self.denominator()) 

  

def _sage_input_(self, sib, coerced): 

r""" 

Produce an expression which will reproduce this value when evaluated. 

  

EXAMPLES:: 

  

sage: sage_input(QQ(1), verify=True) 

# Verified 

QQ(1) 

sage: sage_input(-22/7, verify=True) 

# Verified 

-22/7 

sage: sage_input(-22/7, preparse=False) 

-ZZ(22)/7 

sage: sage_input(10^-50, verify=True) 

# Verified 

1/100000000000000000000000000000000000000000000000000 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: (-2/37)._sage_input_(SageInputBuilder(preparse=False), False) 

{unop:- {binop:/ {call: {atomic:ZZ}({atomic:2})} {atomic:37}}} 

sage: QQ(5)._sage_input_(SageInputBuilder(preparse=False), True) 

{atomic:5} 

""" 

  

# This code is extensively described in the docstring 

# for sage_input.py. 

  

num = self.numerator() 

neg = (num < 0) 

if neg: num = -num 

if self.denominator() == 1: 

if coerced: 

v = sib.int(num) 

else: 

v = sib.name('QQ')(sib.int(num)) 

else: 

v = sib(num)/sib.int(self.denominator()) 

if neg: v = -v 

return v 

  

  

# The except value is just some random double, it doesn't matter what it is. 

cdef double mpq_get_d_nearest(mpq_t x) except? -648555075988944.5: 

""" 

Convert a ``mpq_t`` to a ``double``, with round-to-nearest-even. 

This differs from ``mpq_get_d()`` which does round-to-zero. 

  

TESTS:: 

  

sage: q = QQ(); float(q) 

0.0 

sage: q = 2^-10000; float(q) 

0.0 

sage: float(-q) 

-0.0 

sage: q = 2^10000/1; float(q) 

inf 

sage: float(-q) 

-inf 

  

:: 

  

sage: q = 2^-1075; float(q) 

0.0 

sage: float(-q) 

-0.0 

sage: q = 2^52 / 2^1074; float(q) # Smallest normal double 

2.2250738585072014e-308 

sage: float(-q) 

-2.2250738585072014e-308 

sage: q = (2^52 + 1/2) / 2^1074; float(q) 

2.2250738585072014e-308 

sage: float(-q) 

-2.2250738585072014e-308 

sage: q = (2^52 + 1) / 2^1074; float(q) # Next normal double 

2.225073858507202e-308 

sage: float(-q) 

-2.225073858507202e-308 

sage: q = (2^52 - 1) / 2^1074; float(q) # Largest denormal double 

2.225073858507201e-308 

sage: float(-q) 

-2.225073858507201e-308 

sage: q = 1 / 2^1074; float(q) # Smallest denormal double 

5e-324 

sage: float(-q) 

-5e-324 

sage: q = (1/2) / 2^1074; float(q) 

0.0 

sage: float(-q) 

-0.0 

sage: q = (3/2) / 2^1074; float(q) 

1e-323 

sage: float(-q) 

-1e-323 

sage: q = (2/3) / 2^1074; float(q) 

5e-324 

sage: float(-q) 

-5e-324 

sage: q = (1/3) / 2^1074; float(q) 

0.0 

sage: float(-q) 

-0.0 

sage: q = (2^53 - 1) * 2^971/1; float(q) # Largest double 

1.7976931348623157e+308 

sage: float(-q) 

-1.7976931348623157e+308 

sage: q = (2^53) * 2^971/1; float(q) 

inf 

sage: float(-q) 

-inf 

sage: q = (2^53 - 1/2) * 2^971/1; float(q) 

inf 

sage: float(-q) 

-inf 

sage: q = (2^53 - 2/3) * 2^971/1; float(q) 

1.7976931348623157e+308 

sage: float(-q) 

-1.7976931348623157e+308 

  

AUTHORS: 

  

- Paul Zimmermann, Jeroen Demeyer (:trac:`14416`) 

""" 

cdef mpz_ptr a = mpq_numref(x) 

cdef mpz_ptr b = mpq_denref(x) 

cdef int resultsign = mpz_sgn(a) 

  

if resultsign == 0: 

return 0.0 

  

cdef Py_ssize_t sa = mpz_sizeinbase(a, 2) 

cdef Py_ssize_t sb = mpz_sizeinbase(b, 2) 

  

# Easy case: both numerator and denominator are exactly 

# representable as doubles. 

if sa <= 53 and sb <= 53: 

return mpz_get_d(a) / mpz_get_d(b) 

  

# General case 

  

# We should shift a right by this amount 

cdef Py_ssize_t shift = sa - sb - 54 

  

# At this point, we know that q0 = a/b / 2^shift satisfies 

# 2^53 < q0 < 2^55. 

# The end result d = q0 * 2^shift (rounded). 

  

# Check for obvious overflow/underflow before shifting 

if shift <= -1130: # |d| < 2^-1075 

if resultsign < 0: 

return -0.0 

else: 

return 0.0 

elif shift >= 971: # |d| > 2^1024 

if resultsign < 0: 

return -1.0/0.0 

else: 

return 1.0/0.0 

  

sig_on() 

  

# Compute q = trunc(a / 2^shift) and let remainder_is_zero be True 

# if and only if no truncation occurred. 

cdef mpz_t q, r 

mpz_init(q) 

mpz_init(r) 

cdef int remainder_is_zero 

if shift > 0: 

remainder_is_zero = mpz_divisible_2exp_p(a, shift) 

mpz_tdiv_q_2exp(q, a, shift) 

else: 

mpz_mul_2exp(q, a, -shift) 

remainder_is_zero = True 

  

# Now divide by b to get q = trunc(a/b / 2^shift). 

# remainder_is_zero is True if and only if no truncation occurred 

# (in neither division). 

mpz_tdiv_qr(q, r, q, b) 

if remainder_is_zero: 

remainder_is_zero = (mpz_cmp_ui(r, 0) == 0) 

  

# Convert abs(q) to a 64-bit integer. 

cdef mp_limb_t* q_limbs = (<mpz_ptr>q)._mp_d 

cdef uint64_t q64 

if sizeof(mp_limb_t) >= 8: 

q64 = q_limbs[0] 

else: 

assert sizeof(mp_limb_t) == 4 

q64 = q_limbs[1] 

q64 = (q64 << 32) + q_limbs[0] 

  

mpz_clear(q) 

mpz_clear(r) 

sig_off() 

  

# The quotient q64 has 54 or 55 bits, but we need exactly 54. 

# Shift it down by 1 one if needed. 

cdef Py_ssize_t add_shift 

if q64 < (1ULL << 54): 

add_shift = 0 

else: 

add_shift = 1 

  

if (shift + add_shift) < -1075: 

# The result will be denormal, ensure the final shift is -1075 

# to avoid a double rounding. 

add_shift = -1075 - shift 

  

# Add add_shift to shift and let q = trunc(a/b / 2^shift) 

# for the new shift value. 

cdef uint64_t mask 

if add_shift: 

assert add_shift > 0 

assert add_shift < 64 

shift += add_shift 

# We do an additional division of q by 2^add_shift. 

if remainder_is_zero: 

mask = ((1ULL << add_shift)-1) 

remainder_is_zero = ((q64 & mask) == 0) 

q64 = q64 >> add_shift 

  

# Round q64 from 54 to 53 bits of precision. 

if ((q64 & 1) == 0): 

# Round towards zero 

pass 

else: 

if not remainder_is_zero: 

# Remainder is non-zero: round away from zero 

q64 += 1 

else: 

# Halfway case: round to even 

q64 += (q64 & 2) - 1 

  

# The conversion of q64 to double is *exact*. 

# This is because q64 is even and satisfies q64 <= 2^54, 

# (with 2^53 <= q64 <= 2^54 unless in the denormal case). 

cdef double d = <double>q64 

if resultsign < 0: 

d = -d 

return ldexp(d, shift) 

  

  

def make_rational(s): 

""" 

Make a rational number from ``s`` (a string in base 32) 

  

INPUT: 

  

- ``s`` - string in base 32 

  

OUTPUT: Rational 

  

EXAMPLES:: 

  

sage: (-7/15).str(32) 

'-7/f' 

sage: sage.rings.rational.make_rational('-7/f') 

-7/15 

""" 

r = Rational() 

r._reduce_set(s) 

return r 

  

cdef class Z_to_Q(Morphism): 

r""" 

A morphism from `\ZZ` to `\QQ`. 

""" 

  

def __init__(self): 

""" 

Create morphism from integers to rationals. 

  

EXAMPLES:: 

  

sage: sage.rings.rational.Z_to_Q() 

Natural morphism: 

From: Integer Ring 

To: Rational Field 

""" 

from . import integer_ring 

from . import rational_field 

import sage.categories.homset 

Morphism.__init__(self, sage.categories.homset.Hom(integer_ring.ZZ, rational_field.QQ)) 

  

cpdef Element _call_(self, x): 

""" 

Return the image of the morphism on ``x``. 

  

EXAMPLES:: 

  

sage: sage.rings.rational.Z_to_Q()(2) # indirect doctest 

2 

""" 

cdef Rational rat 

rat = <Rational> Rational.__new__(Rational) 

mpq_set_z(rat.value, (<integer.Integer>x).value) 

return rat 

  

def _repr_type(self): 

""" 

Return string that describes the type of morphism. 

  

EXAMPLES:: 

  

sage: sage.rings.rational.Z_to_Q()._repr_type() 

'Natural' 

""" 

return "Natural" 

  

def section(self): 

""" 

Return a section of this morphism. 

  

EXAMPLES:: 

  

sage: f = QQ.coerce_map_from(ZZ).section(); f 

Generic map: 

From: Rational Field 

To: Integer Ring 

  

This map is a morphism in the category of sets with partial 

maps (see :trac:`15618`):: 

  

sage: f.parent() 

Set of Morphisms from Rational Field to Integer Ring in Category of sets with partial maps 

""" 

from sage.categories.sets_with_partial_maps import SetsWithPartialMaps 

return Q_to_Z(self._codomain.Hom(self.domain(), category=SetsWithPartialMaps())) 

  

def is_surjective(self): 

r""" 

Return whether this morphism is surjective. 

  

EXAMPLES:: 

  

sage: QQ.coerce_map_from(ZZ).is_surjective() 

False 

  

""" 

return False 

  

cdef class Q_to_Z(Map): 

r""" 

A morphism from `\QQ` to `\ZZ`. 

  

TESTS:: 

  

sage: type(ZZ.convert_map_from(QQ)) 

<type 'sage.rings.rational.Q_to_Z'> 

""" 

cpdef Element _call_(self, x): 

""" 

A fast map from the rationals to the integers. 

  

EXAMPLES:: 

  

sage: f = sage.rings.rational.Q_to_Z(QQ, ZZ) 

sage: f(1/2) # indirect doctest 

Traceback (most recent call last): 

... 

TypeError: no conversion of this rational to integer 

sage: f(4/2) # indirect doctest 

2 

""" 

if not mpz_cmp_si(mpq_denref((<Rational>x).value), 1) == 0: 

raise TypeError("no conversion of this rational to integer") 

cdef Integer n = Integer.__new__(Integer) 

n.set_from_mpz(mpq_numref((<Rational>x).value)) 

return n 

  

def section(self): 

""" 

Return a section of this morphism. 

  

EXAMPLES:: 

  

sage: sage.rings.rational.Q_to_Z(QQ, ZZ).section() 

Natural morphism: 

From: Integer Ring 

To: Rational Field 

""" 

return Z_to_Q() 

  

  

cdef class int_to_Q(Morphism): 

r""" 

A morphism from Python 2 ``int`` to `\QQ`. 

""" 

def __init__(self): 

""" 

Initialize ``self``. 

  

EXAMPLES:: 

  

sage: sage.rings.rational.int_to_Q() 

Native morphism: 

From: Set of Python objects of class 'int' 

To: Rational Field 

""" 

from . import rational_field 

import sage.categories.homset 

from sage.structure.parent import Set_PythonType 

Morphism.__init__(self, sage.categories.homset.Hom(Set_PythonType(int), rational_field.QQ)) 

  

cpdef Element _call_(self, a): 

""" 

Return the image of the morphism on ``a``. 

  

EXAMPLES:: 

  

sage: f = sage.rings.rational.int_to_Q() 

sage: f(int(4)) # indirect doctest 

4 

sage: f(4^100) # py2 - this will crash on Python 3 

Traceback (most recent call last): 

... 

TypeError: must be a Python int object 

""" 

  

cdef Rational rat 

  

if type(a) is not int: 

raise TypeError("must be a Python int object") 

  

rat = <Rational> Rational.__new__(Rational) 

mpq_set_si(rat.value, PyInt_AS_LONG(a), 1) 

return rat 

  

def _repr_type(self): 

""" 

Return string that describes the type of morphism. 

  

EXAMPLES:: 

  

sage: sage.rings.rational.int_to_Q()._repr_type() 

'Native' 

""" 

return "Native" 

  

  

cdef class long_to_Q(Morphism): 

r""" 

A morphism from Python 2 ``long``/Python 3 ``int`` to `\QQ`. 

""" 

def __init__(self): 

""" 

Initialize ``self``. 

  

EXAMPLES:: 

  

sage: sage.rings.rational.long_to_Q() # py2 

Native morphism: 

From: Set of Python objects of class 'long' 

To: Rational Field 

sage: sage.rings.rational.long_to_Q() # py3 

Native morphism: 

From: Set of Python objects of class 'int' 

To: Rational Field 

""" 

from . import rational_field 

import sage.categories.homset 

from sage.structure.parent import Set_PythonType 

Morphism.__init__(self, sage.categories.homset.Hom( 

Set_PythonType(long), rational_field.QQ)) 

  

cpdef Element _call_(self, a): 

""" 

Return the image of the morphism on ``a``. 

  

EXAMPLES:: 

  

sage: f = sage.rings.rational.long_to_Q() 

sage: f(long(4)) # indirect doctest 

4 

sage: f(long(4^100)) 

1606938044258990275541962092341162602522202993782792835301376 

""" 

  

cdef Rational rat 

cdef long a_long 

cdef int err = 0 

  

rat = <Rational> Rational.__new__(Rational) 

  

integer_check_long_py(a, &a_long, &err) 

  

if not err: 

mpq_set_si(rat.value, a_long, 1) 

else: 

mpz_set_pylong(mpq_numref(rat.value), a) 

  

return rat 

  

def _repr_type(self): 

""" 

Return string that describes the type of morphism. 

  

EXAMPLES:: 

  

sage: sage.rings.rational.long_to_Q()._repr_type() 

'Native' 

""" 

return "Native"