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

""" 

Lazy real and complex numbers 

  

These classes are very lazy, in the sense that it doesn't really do anything 

but simply sits between exact rings of characteristic 0 and the real numbers. 

The values are actually computed when they are cast into a field of fixed 

precision. 

  

The main purpose of these classes is to provide a place for exact rings (e.g. 

number fields) to embed for the coercion model (as only one embedding can be 

specified in the forward direction). 

""" 

  

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

# Copyright (C) 2008 Robert Bradshaw <robertwb@math.washington.edu> 

# 

# 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, division, print_function 

  

import math 

  

cdef add, sub, mul, truediv, pow, neg, inv 

from operator import add, sub, mul, pow, neg, inv, truediv 

  

cdef canonical_coercion 

from sage.structure.element import canonical_coercion 

from sage.structure.element cimport parent 

from sage.structure.richcmp cimport richcmp 

  

import sage.categories.map 

from sage.categories.morphism cimport Morphism 

from sage.rings.ring cimport Field 

import sage.rings.infinity 

from sage.rings.integer import Integer 

  

cdef QQ, RR, CC, RealField, ComplexField 

from sage.rings.rational_field import QQ 

from sage.rings.real_mpfr import RR, RealField 

from sage.rings.complex_field import ComplexField 

CC = ComplexField(53) 

  

cdef _QQx = None 

  

cdef QQx(): 

global _QQx 

if _QQx is None: 

_QQx = QQ['x'] 

return _QQx 

  

cdef named_unops = [ 'sqrt', 'erf', 'gamma', 'abs', 

'floor', 'ceil', 'trunc', 

'exp', 'log', 'log10', 'log2', 

'sin', 'cos', 'tan', 'arcsin', 'arccos', 'arctan', 

'csc', 'sec', 'cot', 

'sinh', 'cosh', 'tanh', 'arcsinh', 'arccosh', 'arctanh' ] 

  

cdef named_constants = [ 'pi', 'e', 

'euler_constant', 'catalan_constant' ] 

  

cdef class LazyField(Field): 

""" 

The base class for lazy real fields. 

  

.. WARNING:: 

  

LazyField uses :meth:`__getattr__`, to implement:: 

  

sage: CLF.pi 

3.141592653589794? 

  

I (NT, 20/04/2012) did not manage to have ``__getattr__`` call 

:meth:`Parent.__getattr__` in case of failure; hence we can't 

use this ``__getattr__`` trick for extension types to recover 

the methods from categories. Therefore, at this point, no 

concrete subclass of this class should be an extension type 

(which is probably just fine):: 

  

sage: RLF.__class__ 

<class 'sage.rings.real_lazy.RealLazyField_class_with_category'> 

sage: CLF.__class__ 

<class 'sage.rings.real_lazy.ComplexLazyField_class_with_category'> 

""" 

def __init__(self, base=None, names=None, normalize=True, category=None): 

""" 

Initialize ``self``. 

  

EXAMPLES:: 

  

sage: RLF # indirect doctest 

Real Lazy Field 

  

""" 

Field.__init__(self,base or self, names=names, normalize=normalize, category=category) 

  

Element = LazyWrapper 

  

def __getattr__(self, name): 

""" 

Simulates a list of methods found on the real/complex rings. 

  

EXAMPLES:: 

  

sage: a = CLF.pi() * CLF.I(); a 

3.141592653589794?*I 

sage: CDF(a) 

3.141592653589793*I 

""" 

if name in named_constants: 

return LazyConstant(self, name) 

elif name == 'I' and self == CLF: 

return LazyConstant(self, name) 

else: 

raise AttributeError(name) 

  

cpdef _coerce_map_from_(self, R): 

r""" 

The only things that coerce into this ring are exact rings that 

embed into `\RR` or `\CC` (depending on whether this field 

is real or complex), that is, exact rings that coerce into all 

rings into which this ring coerces. 

  

.. NOTE:: 

  

The rings into which this ring coerces are currently the 

corresponding floating-point fields (RealField(p) or 

ComplexField(p)), machine-precision floating-point fields (RDF, 

CDF), and interval fields (RealIntervalField(p), 

ComplexIntervalField(p)). This method should be updated if a new 

parent is added that declares a coercion from RLF/CLF but not from 

one of these, otherwise coercions of elements of type LazyWrapper 

into the new ring might fail. 

  

EXAMPLES:: 

  

sage: RLF.has_coerce_map_from(ZZ) # indirect doctest 

True 

sage: RLF.has_coerce_map_from(QQ) 

True 

sage: RLF.has_coerce_map_from(AA) 

True 

sage: CLF.has_coerce_map_from(QQbar) 

True 

sage: RLF.has_coerce_map_from(RDF) 

False 

  

sage: CLF.has_coerce_map_from(QQ) 

True 

sage: CLF.has_coerce_map_from(QQbar) 

True 

sage: CLF.has_coerce_map_from(CC) 

False 

sage: CLF.has_coerce_map_from(RLF) 

True 

""" 

if isinstance(R, type): 

if R in [int, long]: 

from sage.structure.parent import Set_PythonType 

return LazyWrapperMorphism(Set_PythonType(R), self) 

elif R.is_exact(): 

ivf = self.interval_field() 

mor = ivf.coerce_map_from(R) 

# Indirect coercions might lead to loops both in the coercion 

# discovery algorithm and when trying to convert LazyWrappers, 

# so we only consider direct coercions. 

if mor is not None and not isinstance(mor, sage.categories.map.FormalCompositeMap): 

mor = ivf.middle_field().coerce_map_from(R) 

if mor is not None and not isinstance(mor, sage.categories.map.FormalCompositeMap): 

return LazyWrapperMorphism(R, self) 

# We can skip the test for a coercion to RDF/CDF since RR/CC 

# already coerce into it. 

  

def algebraic_closure(self): 

""" 

Returns the algebraic closure of ``self``, i.e., the complex lazy 

field. 

  

EXAMPLES:: 

  

sage: RLF.algebraic_closure() 

Complex Lazy Field 

  

sage: CLF.algebraic_closure() 

Complex Lazy Field 

""" 

return CLF 

  

cpdef interval_field(self, prec=None): 

""" 

Abstract method to create the corresponding interval field. 

  

TESTS:: 

  

sage: RLF.interval_field() # indirect doctest 

Real Interval Field with 53 bits of precision 

""" 

raise NotImplementedError("subclasses must override this method") 

  

  

class RealLazyField_class(LazyField): 

r""" 

This class represents the set of real numbers to unspecified precision. 

For the most part it simply wraps exact elements and defers evaluation 

until a specified precision is requested. 

  

Its primary use is to connect the exact rings (such as number fields) to 

fixed precision real numbers. For example, to specify an embedding of a 

number field `K` into `\RR` one can map into this field and the 

coercion will then be able to carry the mapping to real fields of any 

precision. 

  

EXAMPLES:: 

  

sage: a = RLF(1/3) 

sage: a 

0.3333333333333334? 

sage: a + 1/5 

0.5333333333333334? 

sage: a = RLF(1/3) 

sage: a 

0.3333333333333334? 

sage: a + 5 

5.333333333333334? 

sage: RealField(100)(a+5) 

5.3333333333333333333333333333 

  

:: 

  

sage: CC.0 + RLF(1/3) 

0.333333333333333 + 1.00000000000000*I 

sage: ComplexField(200).0 + RLF(1/3) 

0.33333333333333333333333333333333333333333333333333333333333 + 1.0000000000000000000000000000000000000000000000000000000000*I 

  

TESTS:: 

  

sage: TestSuite(RLF).run() 

""" 

def interval_field(self, prec=None): 

""" 

Returns the interval field that represents the same mathematical 

field as ``self``. 

  

EXAMPLES:: 

  

sage: RLF.interval_field() 

Real Interval Field with 53 bits of precision 

sage: RLF.interval_field(200) 

Real Interval Field with 200 bits of precision 

""" 

from sage.rings.real_mpfi import RIF, RealIntervalField 

if prec is None: 

return RIF 

else: 

return RealIntervalField(prec) 

  

def construction(self): 

""" 

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

completion of the rationals at infinity to infinite precision. 

  

EXAMPLES:: 

  

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

Rational Field 

sage: RLF == c(S) 

True 

""" 

from sage.categories.pushout import CompletionFunctor 

return CompletionFunctor(sage.rings.infinity.Infinity, 

sage.rings.infinity.Infinity, 

{'type': 'RLF'}), QQ 

  

def _latex_(self): 

r""" 

Return a latex representation of ``self``. 

  

EXAMPLES:: 

  

sage: latex(RLF) # indirect doctest 

\Bold{R} 

""" 

return "\\Bold{R}" 

  

def gen(self, i=0): 

""" 

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

  

EXAMPLES:: 

  

sage: RLF.gen() 

1 

""" 

if i == 0: 

return self(Integer(1)) 

else: 

raise ValueError("RLF has only one generator.") 

  

def _repr_(self): 

""" 

Return a string representation of ``self``. 

  

EXAMPLES:: 

  

sage: RealLazyField() 

Real Lazy Field 

""" 

return "Real Lazy Field" 

  

def __hash__(self): 

""" 

Return the hash of ``self``. 

  

EXAMPLES:: 

  

sage: hash(RLF) % 2^32 == hash(str(RLF)) % 2^32 

True 

""" 

return 1501555429 

  

def __reduce__(self): 

""" 

For pickling. 

  

TESTS:: 

  

sage: RLF == loads(dumps(RLF)) 

True 

sage: RLF is loads(dumps(RLF)) 

True 

""" 

return RealLazyField, () 

  

  

RLF = RealLazyField_class() 

  

def RealLazyField(): 

""" 

Return the lazy real field. 

  

EXAMPLES: 

  

There is only one lazy real field:: 

  

sage: RealLazyField() is RealLazyField() 

True 

""" 

return RLF 

  

  

class ComplexLazyField_class(LazyField): 

""" 

This class represents the set of complex numbers to unspecified precision. 

For the most part it simply wraps exact elements and defers evaluation 

until a specified precision is requested. 

  

For more information, see the documentation of the 

:class:`RLF <sage.rings.real_lazy.RealLazyField_class>`. 

  

EXAMPLES:: 

  

sage: a = CLF(-1).sqrt() 

sage: a 

1*I 

sage: CDF(a) 

1.0*I 

sage: ComplexField(200)(a) 

1.0000000000000000000000000000000000000000000000000000000000*I 

  

TESTS:: 

  

sage: TestSuite(CLF).run(skip=["_test_prod"]) 

  

.. NOTE:: 

  

The following ``TestSuite`` failure:: 

  

sage: CLF._test_prod() 

Traceback (most recent call last): 

... 

AssertionError: False is not true 

  

is due to (acceptable?) numerical noise:: 

  

sage: x = CLF.I 

sage: x*x == x^2 

False 

sage: x*x 

-1 

sage: x^2 

-0.9999999999999999? + 0.?e-15*I 

""" 

def __init__(self): 

""" 

This lazy field doesn't evaluate its elements until they are cast into 

a field of fixed precision. 

  

EXAMPLES: 

sage: a = RLF(1/3); a 

0.3333333333333334? 

sage: Reals(200)(a) 

0.33333333333333333333333333333333333333333333333333333333333 

""" 

LazyField.__init__(self, base=RLF) 

self._populate_coercion_lists_(coerce_list=[LazyWrapperMorphism(RLF, self)]) 

  

def interval_field(self, prec=None): 

""" 

Returns the interval field that represents the same mathematical 

field as ``self``. 

  

EXAMPLES:: 

  

sage: CLF.interval_field() 

Complex Interval Field with 53 bits of precision 

sage: CLF.interval_field(333) 

Complex Interval Field with 333 bits of precision 

sage: CLF.interval_field() is CIF 

True 

""" 

from sage.rings.all import CIF, ComplexIntervalField 

if prec is None: 

return CIF 

else: 

return ComplexIntervalField(prec) 

  

def gen(self, i=0): 

""" 

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

  

EXAMPLES:: 

  

sage: CLF.gen() 

1*I 

sage: ComplexField(100)(CLF.gen()) 

1.0000000000000000000000000000*I 

""" 

if i == 0: 

from sage.rings.complex_double import CDF 

return LazyAlgebraic(self, [1, 0, 1], CDF.gen()) 

else: 

raise ValueError("CLF has only one generator.") 

  

def construction(self): 

""" 

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

algebraic closure of the real lazy field. 

  

EXAMPLES:: 

  

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

Real Lazy Field 

sage: CLF == c(S) 

True 

""" 

from sage.categories.pushout import AlgebraicClosureFunctor 

return (AlgebraicClosureFunctor(), RLF) 

  

def _latex_(self): 

r""" 

Return a latex representation of ``self``. 

  

EXAMPLES:: 

  

sage: latex(CLF) # indirect doctest 

\Bold{C} 

""" 

return "\\Bold{C}" 

  

def _repr_(self): 

""" 

Return a string representation of ``self``. 

  

EXAMPLES:: 

  

sage: CLF 

Complex Lazy Field 

""" 

return "Complex Lazy Field" 

  

def __hash__(self): 

""" 

Return the hash of ``self``. 

  

EXAMPLES:: 

  

sage: hash(CLF) % 2^32 == hash(str(CLF)) % 2^32 

True 

""" 

return -1382606040 

  

def __reduce__(self): 

""" 

For pickling. 

  

TESTS:: 

  

sage: CLF == loads(dumps(CLF)) 

True 

sage: CLF is loads(dumps(CLF)) 

True 

""" 

return ComplexLazyField, () 

  

  

CLF = ComplexLazyField_class() 

  

def ComplexLazyField(): 

""" 

Returns the lazy complex field. 

  

EXAMPLES: 

  

There is only one lazy complex field:: 

  

sage: ComplexLazyField() is ComplexLazyField() 

True 

""" 

return CLF 

  

  

  

cdef int get_new_prec(R, int depth) except -1: 

""" 

There are depth operations, so we want at least that many more digits of 

precision. 

  

Field creation may be expensive, so we want to avoid incrementing by 1 so 

that it is more likely for cached fields to be used. 

""" 

cdef int needed_prec = R.prec() 

needed_prec += depth 

if needed_prec % 10 != 0: 

needed_prec += 10 - needed_prec % 10 

return needed_prec 

  

  

cdef class LazyFieldElement(FieldElement): 

  

cpdef _add_(left, right): 

""" 

Add ``left`` with ``right``. 

  

EXAMPLES:: 

  

sage: RLF(5) + RLF(1/2) # indirect doctest 

5.5000000000000000? 

""" 

if isinstance(left, LazyWrapper) and isinstance(right, LazyWrapper): 

try: 

return left._new_wrapper((<LazyWrapper?>left)._value + (<LazyWrapper?>right)._value) 

except TypeError: 

pass 

return left._new_binop(left, right, add) 

  

cpdef _sub_(left, right): 

""" 

Subtract ``right`` from ``left``. 

  

EXAMPLES:: 

  

sage: CLF(5) - 2 # indirect doctest 

3 

""" 

if isinstance(left, LazyWrapper) and isinstance(right, LazyWrapper): 

try: 

return left._new_wrapper((<LazyWrapper?>left)._value - (<LazyWrapper?>right)._value) 

except TypeError: 

pass 

return left._new_binop(left, right, sub) 

  

cpdef _mul_(left, right): 

""" 

Mutliply ``left`` with ``right``. 

  

EXAMPLES:: 

  

sage: CLF(10) * RLF(5) # indirect doctest 

50 

""" 

if isinstance(left, LazyWrapper) and isinstance(right, LazyWrapper): 

try: 

return left._new_wrapper((<LazyWrapper?>left)._value * (<LazyWrapper?>right)._value) 

except TypeError: 

pass 

return left._new_binop(left, right, mul) 

  

cpdef _div_(left, right): 

""" 

Divide ``left`` by ``right``. 

  

EXAMPLES:: 

  

sage: a = RLF(1) / RLF(6); a # indirect doctest 

0.1666666666666667? 

sage: Reals(300)(a) 

0.166666666666666666666666666666666666666666666666666666666666666666666666666666666666666667 

""" 

if isinstance(left, LazyWrapper) and isinstance(right, LazyWrapper): 

try: 

return left._new_wrapper((<LazyWrapper?>left)._value / (<LazyWrapper?>right)._value) 

except TypeError: 

pass 

return left._new_binop(left, right, truediv) 

  

def __pow__(left, right, dummy): 

""" 

Raise ``left`` to the ``right`` power. 

  

EXAMPLES:: 

  

sage: a = RLF(2) ^ (1/2); a 

1.414213562373095? 

sage: Reals(300)(a) 

1.41421356237309504880168872420969807856967187537694807317667973799073247846210703885038753 

""" 

if isinstance(left, LazyWrapper) and isinstance(right, LazyWrapper): 

try: 

return left._new_wrapper((<LazyWrapper>left)._value ** (<LazyWrapper>right)._value) 

except TypeError: 

pass 

if not isinstance(left, LazyFieldElement): 

left = (<LazyFieldElement>right)._new_wrapper(left) 

elif not isinstance(right, LazyFieldElement): 

right = (<LazyFieldElement>left)._new_wrapper(right) 

return (<LazyFieldElement>left)._new_binop(left, right, pow) 

  

def __neg__(self): 

""" 

Return the negation of ``self``. 

  

EXAMPLES:: 

  

sage: -RLF(7) 

-7 

""" 

return self._new_unop(self, neg) 

  

def __invert__(self): 

""" 

Take the reciprocal of ``self``. 

  

EXAMPLES:: 

  

sage: a = ~RLF(6); a 

0.1666666666666667? 

sage: Reals(90)(a) 

0.16666666666666666666666667 

""" 

return self._new_unop(self, inv) 

  

cpdef _richcmp_(self, other, int op): 

""" 

If things are being wrapped, tries to compare values. That failing, it 

tries to compare intervals, which may return a false negative. 

  

EXAMPLES:: 

  

sage: RLF(3) == RLF(9/3) 

True 

sage: RLF(3) == RLF(4) 

False 

sage: RLF(3) < RLF(5/3) 

False 

  

TESTS:: 

  

sage: from sage.rings.real_lazy import LazyBinop 

sage: RLF(3) < LazyBinop(RLF, 5, 3, operator.truediv) 

False 

sage: from sage.rings.real_lazy import LazyWrapper 

sage: LazyWrapper(RLF, 3) < LazyWrapper(RLF, 5/3) 

False 

sage: from sage.rings.real_lazy import LazyUnop 

sage: RLF(3) < LazyUnop(RLF, 2, sqrt) 

False 

sage: from sage.rings.real_lazy import LazyNamedUnop 

sage: RLF(3) < LazyNamedUnop(RLF, 0, 'sin') 

False 

sage: from sage.rings.real_lazy import LazyConstant 

sage: RLF(3) < LazyConstant(RLF, 'e') 

False 

""" 

left = self 

try: 

if isinstance(self, LazyWrapper) and isinstance(other, LazyWrapper): 

left, right = canonical_coercion((<LazyWrapper>self)._value, (<LazyWrapper>other)._value) 

return richcmp(left, right, op) 

except TypeError: 

pass 

left, right = self.approx(), other.approx() 

return richcmp(left.endpoints(), right.endpoints(), op) 

  

def __hash__(self): 

""" 

Return the hash value of ``self``. 

  

EXAMPLES:: 

  

sage: a = RLF(3) 

sage: hash(a) 

3 

""" 

return hash(complex(self)) 

  

cdef LazyFieldElement _new_wrapper(self, value): 

cdef LazyWrapper e = <LazyWrapper>LazyWrapper.__new__(LazyWrapper) 

e._parent = self._parent 

e._value = value 

return e 

  

cdef LazyFieldElement _new_binop(self, LazyFieldElement left, LazyFieldElement right, op): 

cdef LazyBinop e = <LazyBinop>LazyBinop.__new__(LazyBinop) 

e._parent = self._parent 

e._left = left 

e._right = right 

e._op = op 

return e 

  

cdef LazyFieldElement _new_unop(self, LazyFieldElement arg, op): 

cdef LazyUnop e = <LazyUnop>LazyUnop.__new__(LazyUnop) 

e._parent = self._parent 

e._op = op 

e._arg = arg 

return e 

  

def _repr_(self): 

""" 

The string representation of ``self`` is an interval in which 

``self`` is contained. 

  

EXAMPLES:: 

  

sage: RLF(3) # indirect doctest 

3 

sage: RLF(1/3) 

0.3333333333333334? 

""" 

return str(self.approx()) 

  

def approx(self): 

""" 

Returns ``self`` as an element of an interval field. 

  

EXAMPLES:: 

  

sage: CLF(1/6).approx() 

0.1666666666666667? 

sage: CLF(1/6).approx().parent() 

Complex Interval Field with 53 bits of precision 

  

When the absolute value is involved, the result might be real:: 

  

sage: z = exp(CLF(1 + I/2)); z 

2.38551673095914? + 1.303213729686996?*I 

sage: r = z.abs(); r 

2.71828182845905? 

sage: parent(z.approx()) 

Complex Interval Field with 53 bits of precision 

sage: parent(r.approx()) 

Real Interval Field with 53 bits of precision 

""" 

return self.eval(self._parent.interval_field()) 

  

def _real_double_(self, R): 

""" 

Return ``self`` as a real double. 

  

EXAMPLES:: 

  

sage: a = RLF(3) 

sage: RDF(a) # indirect doctest 

3.0 

""" 

return self.eval(R) 

  

def _complex_double_(self, R): 

""" 

Return ``self`` as a complex double. 

  

EXAMPLES:: 

  

sage: a = RLF(5) 

sage: CDF(a) # indirect doctest 

5.0 

sage: a = CLF(-1)^(1/4) 

sage: CDF(a) 

0.7071067811865476 + 0.7071067811865475*I 

""" 

return self.eval(R) 

  

def _generic_(self, R): 

""" 

Return ``self`` in a generic ring ``R``. 

  

EXAMPLES:: 

  

sage: a = RLF(2/3) 

sage: RR(a) # indirect doctest 

0.666666666666667 

sage: RR(a^2) 

0.444444444444444 

""" 

return self.eval(R) 

  

_real_mpfi_ = _complex_mpfi_ =_mpfr_ = _complex_mpfr_field_ = _generic_ 

  

def __complex__(self): 

""" 

Return ``self`` as a complex. 

  

EXAMPLES:: 

  

sage: complex(CLF(-1)^(1/4)) 

(0.707106781186547...+0.707106781186547...j) 

""" 

try: 

return self.eval(complex) 

except Exception: 

from .complex_field import ComplexField 

return complex(self.eval(ComplexField(53))) 

  

cpdef eval(self, R): 

""" 

Abstract method for converting ``self`` into an element of ``R``. 

  

EXAMPLES:: 

  

sage: a = RLF(12) 

sage: a.eval(ZZ) 

12 

""" 

raise NotImplementedError("Subclasses must override this method.") 

  

cpdef int depth(self): 

""" 

Abstract method for returning the depth of ``self`` as an arithmetic 

expression. 

  

This is the maximum number of dependent intermediate expressions when 

evaluating ``self``, and is used to determine the precision needed to 

get the final result to the desired number of bits. 

  

It is equal to the maximum of the right and left depths, plus one. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyBinop 

sage: a = LazyBinop(RLF, 6, 8, operator.mul) 

sage: a.depth() 

1 

""" 

raise NotImplementedError("Subclasses must override this method.") 

  

def __dir__(self): 

""" 

Adds the named_unops to ``__dir__`` so that tab completion works. 

  

TESTS:: 

  

sage: "log" in RLF(sqrt(8)).__dir__() 

True 

  

""" 

return FieldElement.__dir__(self) + named_unops 

  

def __getattribute__(self, name): 

""" 

Simulates a list of methods found on the real/complex mpfr classes. 

  

EXAMPLES:: 

  

sage: a = RLF(3) 

sage: a.sqrt() 

1.732050807568878? 

sage: sin(a) 

0.1411200080598673? 

sage: RealField(160)(tanh(RLF(3))) 

0.99505475368673045133188018525548847509781385470 

""" 

if name in named_unops: 

return LazyNamedUnop(self._parent, self, name) 

else: 

return FieldElement.__getattribute__(self, name) 

  

def continued_fraction(self): 

r""" 

Return the continued fraction of self. 

  

EXAMPLES:: 

  

sage: a = RLF(sqrt(2)) + RLF(sqrt(3)) 

sage: cf = a.continued_fraction() 

sage: cf 

[3; 6, 1, 5, 7, 1, 1, 4, 1, 38, 43, 1, 3, 2, 1, 1, 1, 1, 2, 4, ...] 

sage: cf.convergent(100) 

444927297812646558239761867973501208151173610180916865469/141414466649174973335183571854340329919207428365474086063 

""" 

from sage.rings.continued_fraction import ContinuedFraction_real 

return ContinuedFraction_real(self) 

  

  

def make_element(parent, *args): 

""" 

Create an element of ``parent``. 

  

EXAMPLES:: 

  

sage: a = RLF(pi) + RLF(sqrt(1/2)) # indirect doctest 

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

True 

""" 

return parent(*args) 

  

cdef class LazyWrapper(LazyFieldElement): 

  

cpdef int depth(self): 

""" 

Returns the depth of ``self`` as an expression, which is always 0. 

  

EXAMPLES:: 

  

sage: RLF(4).depth() 

0 

""" 

return 0 

  

def __init__(self, LazyField parent, value, check=True): 

""" 

A lazy element that simply wraps an element of another ring. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyWrapper 

sage: a = LazyWrapper(RLF, 3) 

sage: a._value 

3 

""" 

FieldElement.__init__(self, parent) 

self._value = value 

if check: 

self._parent.interval_field()(value) 

  

def __neg__(self): 

""" 

Return the negation of ``self``. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyWrapper 

sage: a = LazyWrapper(RLF, 3) 

sage: (-a)._value 

-3 

""" 

return self._new_wrapper(-self._value) 

  

def __invert__(self): 

""" 

Return the reciprocal of ``self``. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyWrapper 

sage: a = LazyWrapper(RLF, 23) 

sage: ~a 

0.04347826086956522? 

sage: (~a)._value 

1/23 

""" 

return self._new_wrapper(~self._value) 

  

def __float__(self): 

""" 

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyWrapper 

sage: a = LazyWrapper(CLF, 19) 

sage: float(a) 

19.0 

""" 

return <double>self._value 

  

def __nonzero__(self): 

""" 

Check to see if ``self`` is not zero. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyWrapper 

sage: not LazyWrapper(RLF, 1) 

False 

sage: not LazyWrapper(RLF, 0) 

True 

""" 

return not not self._value 

  

def __hash__(self): 

""" 

Return the hash value of ``self``. 

  

EXAMPLES:: 

  

sage: hash(CLF(-1)) 

-2 

sage: hash(RLF(9/4)) == hash(9/4) 

True 

""" 

return hash(self._value) 

  

cpdef eval(self, R): 

""" 

Convert ``self`` into an element of ``R``. 

  

EXAMPLES:: 

  

sage: a = RLF(12) 

sage: a.eval(ZZ) 

12 

sage: a.eval(ZZ).parent() 

Integer Ring 

""" 

try: 

mor = R.convert_map_from(parent(self._value)) 

except AttributeError: 

return R(self._value) 

if mor is not None and self.parent() not in mor.domains(): 

return mor(self._value) 

else: 

raise TypeError("unable to convert {!r} to an element of {}".format(self._value, R)) 

  

def __reduce__(self): 

""" 

For pickling. 

  

TESTS:: 

  

sage: a = RLF(2) 

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

True 

""" 

return make_element, (self._parent, self._value) 

  

def continued_fraction(self): 

r""" 

Return the continued fraction of self. 

  

EXAMPLES:: 

  

sage: a = RLF(sqrt(2)) 

sage: a.continued_fraction() 

[1; 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, ...] 

""" 

from sage.rings.continued_fraction import ContinuedFraction_real, ContinuedFraction_infinite 

if isinstance(self._value, (ContinuedFraction_infinite, ContinuedFraction_real)): 

return self._value 

return ContinuedFraction_real(self) 

  

  

cdef class LazyBinop(LazyFieldElement): 

  

def __init__(self, LazyField parent, left, right, op): 

""" 

A lazy element representing a binary (usually arithmetic) operation 

between two other lazy elements. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyBinop 

sage: a = LazyBinop(RLF, 2, 1/3, operator.add) 

sage: a 

2.333333333333334? 

sage: Reals(200)(a) 

2.3333333333333333333333333333333333333333333333333333333333 

""" 

FieldElement.__init__(self, parent) 

if not isinstance(left, LazyFieldElement): 

left = self._new_wrapper(left) 

if not isinstance(right, LazyFieldElement): 

right = self._new_wrapper(right) 

self._left = left 

self._right = right 

self._op = op 

  

cpdef int depth(self): 

""" 

Return the depth of ``self`` as an arithmetic expression. 

  

This is the maximum number of dependent intermediate expressions when 

evaluating ``self``, and is used to determine the precision needed to 

get the final result to the desired number of bits. 

  

It is equal to the maximum of the right and left depths, plus one. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyBinop 

sage: a = LazyBinop(RLF, 6, 8, operator.mul) 

sage: a.depth() 

1 

sage: b = LazyBinop(RLF, 2, a, operator.sub) 

sage: b.depth() 

2 

""" 

cdef int left = self._left.depth() 

cdef int right = self._right.depth() 

return 1 + (left if left > right else right) 

  

cpdef eval(self, R): 

""" 

Convert the operands to elements of ``R``, then perform the operation 

on them. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyBinop 

sage: a = LazyBinop(RLF, 6, 8, operator.add) 

sage: a.eval(RR) 

14.0000000000000 

  

A bit absurd:: 

  

sage: a.eval(str) 

'68' 

""" 

left = self._left.eval(R) 

right = self._right.eval(R) 

if self._op is add: 

return left + right 

elif self._op is mul: 

return left * right 

elif self._op is sub: 

return left - right 

elif self._op is truediv: 

return left / right 

elif self._op is pow: 

return left ** right 

else: 

# We only do a call after testing the above because it is a python call. 

return self._op(left, right) 

  

def __float__(self): 

""" 

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyBinop 

sage: a = LazyBinop(RLF, 3, 1/2, operator.sub) 

sage: float(a) 

2.5 

sage: type(float(a)) 

<... 'float'> 

""" 

cdef double left = self._left 

cdef double right = self._right 

if self._op is add: 

return left + right 

elif self._op is mul: 

return left * right 

elif self._op is sub: 

return left - right 

elif self._op is truediv: 

return left / right 

elif self._op is pow: 

return left ** right 

else: 

# We only do a call here because it is a python call. 

return self._op(left, right) 

  

def __hash__(self): 

""" 

Return the hash value of ``self``. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyBinop 

sage: a = LazyBinop(RLF, 5, 1/2, operator.sub) 

sage: hash(a) 

-1607638785 # 32-bit 

-7461864723258187521 # 64-bit 

""" 

return hash(self._op(hash(self._left), hash(self._right))) 

  

def __reduce__(self): 

""" 

For pickling. 

  

TESTS:: 

  

sage: from sage.rings.real_lazy import LazyBinop 

sage: a = LazyBinop(CLF, 3, 2, operator.truediv) 

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

True 

""" 

return make_element, (LazyBinop, self._parent, self._left, self._right, self._op) 

  

  

cdef class LazyUnop(LazyFieldElement): 

  

def __init__(self, LazyField parent, arg, op): 

""" 

Represents a unevaluated single function of one variable. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyUnop 

sage: a = LazyUnop(RLF, 3, sqrt); a 

1.732050807568878? 

sage: a._arg 

3 

sage: a._op 

<function sqrt at ...> 

sage: Reals(100)(a) 

1.7320508075688772935274463415 

sage: Reals(100)(a)^2 

3.0000000000000000000000000000 

""" 

FieldElement.__init__(self, parent) 

if not isinstance(arg, LazyFieldElement): 

arg = self._new_wrapper(arg) 

self._op = op 

self._arg = arg 

  

cpdef int depth(self): 

""" 

Return the depth of ``self`` as an arithmetic expression. 

  

This is the maximum number of dependent intermediate expressions when 

evaluating ``self``, and is used to determine the precision needed to 

get the final result to the desired number of bits. 

  

It is equal to one more than the depth of its operand. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyUnop 

sage: a = LazyUnop(RLF, 3, sqrt) 

sage: a.depth() 

1 

sage: b = LazyUnop(RLF, a, sin) 

sage: b.depth() 

2 

""" 

return 1 + self._arg.depth() 

  

cpdef eval(self, R): 

""" 

Convert ``self`` into an element of ``R``. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyUnop 

sage: a = LazyUnop(RLF, 3, sqrt) 

sage: a.eval(ZZ) 

sqrt(3) 

""" 

arg = self._arg.eval(R) 

if self._op is neg: 

return -arg 

elif self._op is inv: 

return ~arg 

return self._op(self._arg.eval(R)) 

  

def __hash__(self): 

""" 

Return the hash value of ``self``. 

  

EXAMPLES:: 

  

sage: hash(RLF(sin(1))) == hash(RLF(sin(1))) 

True 

""" 

return hash(self._op(hash(self._arg))) 

  

def __float__(self): 

""" 

Convert ``self`` into a floating point. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyUnop 

sage: a = LazyUnop(RLF, 3, sqrt) 

sage: float(a) 

1.7320508075688772 

""" 

return self._op(<double>self._arg) 

  

def __reduce__(self): 

""" 

For pickling. 

  

TESTS:: 

  

sage: from sage.rings.real_lazy import LazyUnop 

sage: a = LazyUnop(RLF, 7, sqrt) 

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

True 

""" 

return make_element, (LazyUnop, self._parent, self._arg, self._op) 

  

  

cdef class LazyNamedUnop(LazyUnop): 

  

def __init__(self, LazyField parent, arg, op, extra_args=None): 

""" 

This class is used to represent the many named methods attached to real 

numbers, and is instantiated by the ``__getattr__`` method of 

:class:`LazyElements`. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyNamedUnop 

sage: a = LazyNamedUnop(RLF, 1, 'arcsin') 

sage: RR(a) 

1.57079632679490 

sage: a = LazyNamedUnop(RLF, 9, 'log', extra_args=(3,)) 

sage: RR(a) 

2.00000000000000 

""" 

LazyUnop.__init__(self, parent, arg, op) 

if extra_args is not None and not isinstance(extra_args, tuple): 

raise TypeError("extra args must be a tuple") 

self._extra_args = extra_args 

  

cpdef eval(self, R): 

""" 

Convert ``self`` into an element of ``R``. 

  

TESTS:: 

  

sage: from sage.rings.real_lazy import LazyNamedUnop 

sage: a = LazyNamedUnop(RLF, 4, 'sqrt') 

sage: RR(a) # indirect doctest 

2.00000000000000 

sage: a.sqrt() 

1.414213562373095? 

sage: RealField(212)(a) 

2.00000000000000000000000000000000000000000000000000000000000000 

sage: float(a) 

2.0 

  

Now for some extra arguments:: 

  

sage: a = RLF(100) 

sage: a.log(10) 

2 

sage: float(a.log(10)) 

2.0 

""" 

arg = self._arg.eval(R) 

cdef bint has_extra_args = self._extra_args is not None and len(self._extra_args) > 0 

if type(R) is type: 

f = getattr(math, self._op) 

if has_extra_args: 

return f(arg, *self._extra_args) 

else: 

return f(arg) 

else: 

f = getattr(arg, self._op) 

if has_extra_args: 

return f(*self._extra_args) 

else: 

return f() 

  

def approx(self): 

""" 

Does something reasonable with functions that are not defined on the 

interval fields. 

  

TESTS:: 

  

sage: from sage.rings.real_lazy import LazyNamedUnop 

sage: LazyNamedUnop(RLF, 8, 'sqrt') # indirect doctest 

2.828427124746190? 

""" 

try: 

return LazyUnop.approx(self) 

except AttributeError: 

# not everything defined on interval fields 

# this is less info though, but mostly just want to print it 

interval_field = self._parent.interval_field() 

return self.eval(interval_field.middle_field()) 

  

def __hash__(self): 

""" 

Return the hash value of ``self``. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyNamedUnop 

sage: a = LazyNamedUnop(RLF, 1, 'sin') 

sage: hash(a) 

2110729788 

""" 

return hash(complex(self)) 

  

def __float__(self): 

""" 

TESTS:: 

  

sage: from sage.rings.real_lazy import LazyNamedUnop 

sage: a = LazyNamedUnop(RLF, 1, 'sin') 

sage: float(a) 

0.8414709848078965 

""" 

return self.eval(float) 

  

def __call__(self, *args): 

""" 

TESTS:: 

  

sage: a = RLF(32) 

sage: a.log(2) 

5 

sage: float(a.log(2)) 

5.0 

  

What is going on here in the background is:: 

  

sage: from sage.rings.real_lazy import LazyNamedUnop 

sage: b = LazyNamedUnop(RLF, a, 'log') 

sage: b(2) 

5 

sage: b(2)._extra_args 

(2,) 

""" 

self._extra_args = args 

return self 

  

def __reduce__(self): 

""" 

TESTS:: 

  

sage: from sage.rings.real_lazy import LazyNamedUnop 

sage: a = LazyNamedUnop(RLF, 1, 'sin') 

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

True 

""" 

return make_element, (LazyNamedUnop, self._parent, self._arg, self._op, self._extra_args) 

  

cdef class LazyConstant(LazyFieldElement): 

  

cdef readonly _name 

cdef readonly _extra_args 

cdef readonly bint _is_special 

  

def __init__(self, LazyField parent, name, extra_args=None): 

""" 

This class represents a real or complex constant (such as ``pi`` 

or ``I``). 

  

TESTS:: 

  

sage: a = RLF.pi(); a 

3.141592653589794? 

sage: RealField(300)(a) 

3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482 

  

sage: from sage.rings.real_lazy import LazyConstant 

sage: a = LazyConstant(RLF, 'euler_constant') 

sage: RealField(200)(a) 

0.57721566490153286060651209008240243104215933593992359880577 

""" 

LazyFieldElement.__init__(self, parent) 

self._name = name 

self._extra_args = extra_args 

self._is_special = name in ['e', 'I'] 

  

cpdef eval(self, R): 

""" 

Convert ``self`` into an element of ``R``. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyConstant 

sage: a = LazyConstant(RLF, 'e') 

sage: RDF(a) # indirect doctest 

2.718281828459045 

sage: a = LazyConstant(CLF, 'I') 

sage: CC(a) 

1.00000000000000*I 

""" 

if self._is_special: 

if self._name == 'e': 

return R(1).exp() 

elif self._name == 'I': 

I = R.gen() 

if I*I < 0: 

return I 

else: 

raise TypeError("The complex constant I is not in this real field.") 

f = getattr(R, self._name) 

if self._extra_args is None: 

return f() 

else: 

return f(*self._extra_args) 

  

def __call__(self, *args): 

""" 

TESTS:: 

  

sage: CLF.I() 

1*I 

sage: CDF(CLF.I()) 

1.0*I 

""" 

self._extra_args = args 

return self 

  

def __hash__(self): 

""" 

Return the hash value of ``self``. 

  

TESTS:: 

  

sage: from sage.rings.real_lazy import LazyConstant 

sage: a = LazyConstant(RLF, 'e') 

sage: hash(a) 

2141977644 

""" 

return hash(complex(self)) 

  

def __float__(self): 

""" 

TESTS:: 

  

sage: from sage.rings.real_lazy import LazyConstant 

sage: a = LazyConstant(RLF, 'pi') 

sage: float(a) 

3.141592653589793 

""" 

interval_field = self._parent.interval_field() 

return <double>self.eval(interval_field.middle_field()) 

  

def __reduce__(self): 

""" 

TESTS:: 

  

sage: from sage.rings.real_lazy import LazyConstant 

sage: a = LazyConstant(RLF, 'pi') 

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

True 

""" 

return make_element, (LazyConstant, self._parent, self._name, self._extra_args) 

  

  

cdef class LazyAlgebraic(LazyFieldElement): 

  

cdef readonly _poly 

cdef readonly _root_approx 

cdef readonly int _prec 

cdef readonly _quadratic_disc 

cdef readonly _root 

  

def __init__(self, parent, poly, approx, int prec=0): 

r""" 

This represents an algebraic number, specified by a polynomial over 

`\QQ` and a real or complex approximation. 

  

EXAMPLES:: 

  

sage: x = polygen(QQ) 

sage: from sage.rings.real_lazy import LazyAlgebraic 

sage: a = LazyAlgebraic(RLF, x^2-2, 1.5) 

sage: a 

1.414213562373095? 

""" 

LazyFieldElement.__init__(self, parent) 

self._poly = QQx()(poly) 

self._root = None 

if prec is None: 

prec = approx.parent().prec() 

self._prec = prec 

if self._poly.degree() == 2: 

c, b, a = self._poly.list() 

self._quadratic_disc = b*b - 4*a*c 

if isinstance(parent, RealLazyField_class): 

from sage.rings.real_double import RDF 

if len(self._poly.roots(RDF)) == 0: 

raise ValueError("%s has no real roots" % self._poly) 

approx = (RR if prec == 0 else RealField(prec))(approx) 

else: 

approx = (CC if prec == 0 else ComplexField(prec))(approx) 

self._root_approx = approx 

  

cpdef eval(self, R): 

""" 

Convert ``self`` into an element of ``R``. 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyAlgebraic 

sage: a = LazyAlgebraic(CLF, QQ['x'].cyclotomic_polynomial(7), 0.6+0.8*CC.0) 

sage: a 

0.6234898018587335? + 0.7818314824680299?*I 

sage: ComplexField(150)(a) # indirect doctest 

0.62348980185873353052500488400423981063227473 + 0.78183148246802980870844452667405775023233452*I 

  

sage: a = LazyAlgebraic(CLF, QQ['x'].0^2-7, -2.0) 

sage: RR(a) 

-2.64575131106459 

sage: RR(a)^2 

7.00000000000000 

""" 

if isinstance(R, type): 

if self._prec < 53: 

self.eval(self.parent().interval_field(64)) # up the prec 

elif R.is_exact() or self._prec < R.prec(): 

# Carl Witty said: 

# Quadratic equation faster and more accurate than roots(), 

# but the current code doesn't do the right thing with interval 

# arithmetic (it returns a point interval) so it's being disabled 

# for now 

# if self._quadratic_disc is not None: 

# c, b, a = self._poly.list() 

# if self._root_approx.real() < -b/2*a: 

# z = (-b - R(self._quadratic_disc).sqrt()) / (2*a) 

# else: 

# z = (-b + R(self._quadratic_disc).sqrt()) / (2*a) 

# if z.parent() is not R: 

# z = R(z) 

# self._root_approx = z 

# from sage.rings.complex_interval_field import is_IntervalField 

# if is_IntervalField(R): 

# self._root_approx = (self._root_approx.upper() + self._root_approx.lower()) / 2 

# self._prec = R.prec() 

# return R(self._root_approx) 

if self._root is None: 

# This could be done much more efficiently with Newton iteration, 

# but will require some care to make sure we get the right root, and 

# to the correct precision. 

from sage.rings.qqbar import AA, QQbar 

roots = self._poly.roots(ring = AA if isinstance(self._parent, RealLazyField_class) else QQbar) 

best_root = roots[0][0] 

min_dist = abs(self._root_approx - best_root) 

for r, e in roots[1:]: 

dist = abs(self._root_approx - r) 

if dist < min_dist: 

best_root = r 

min_dist = dist 

self._root = best_root 

if self._root is not None: 

return R(self._root) 

  

def __float__(self): 

""" 

TESTS:: 

  

sage: x = polygen(QQ) 

sage: from sage.rings.real_lazy import LazyAlgebraic 

sage: a = LazyAlgebraic(RLF, x^3-10, 1.5) 

sage: float(a) 

2.154434690031883... 

""" 

return self.eval(float) 

  

def __reduce__(self): 

""" 

TESTS:: 

  

sage: from sage.rings.real_lazy import LazyAlgebraic 

sage: a = LazyAlgebraic(RLF, x^2-2, 1.5) 

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

True 

""" 

return make_element, (LazyAlgebraic, self._parent, self._poly, self._root_approx, self._prec) 

  

  

cdef class LazyWrapperMorphism(Morphism): 

  

def __init__(self, domain, LazyField codomain): 

""" 

This morphism coerces elements from anywhere into lazy rings 

by creating a wrapper element (as fast as possible). 

  

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyWrapperMorphism 

sage: f = LazyWrapperMorphism(QQ, RLF) 

sage: a = f(3); a 

3 

sage: type(a) 

<type 'sage.rings.real_lazy.LazyWrapper'> 

sage: a._value 

3 

sage: a._value.parent() 

Rational Field 

""" 

from sage.categories.homset import Hom 

Morphism.__init__(self, Hom(domain, codomain)) 

  

cpdef Element _call_(self, x): 

""" 

EXAMPLES:: 

  

sage: from sage.rings.real_lazy import LazyWrapperMorphism 

sage: f = LazyWrapperMorphism(QQ, CLF) 

sage: a = f(1/3); a # indirect doctest 

0.3333333333333334? 

sage: type(a) 

<type 'sage.rings.real_lazy.LazyWrapper'> 

sage: Reals(100)(a) 

0.33333333333333333333333333333 

  

Note that it doesn't double-wrap lazy elements:: 

  

sage: f = LazyWrapperMorphism(RLF, CLF) 

sage: x = RLF(20) 

sage: f(x) 

20 

sage: f(x)._value 

20 

""" 

cdef LazyWrapper e = <LazyWrapper>LazyWrapper.__new__(LazyWrapper) 

e._parent = self._codomain 

if type(x) is LazyWrapper: 

e._value = (<LazyWrapper>x)._value 

else: 

e._value = x 

return e