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

""" 

There are three types of functions implemented in SymPy: 

 

1) defined functions (in the sense that they can be evaluated) like 

exp or sin; they have a name and a body: 

f = exp 

2) undefined function which have a name but no body. Undefined 

functions can be defined using a Function class as follows: 

f = Function('f') 

(the result will be a Function instance) 

3) anonymous function (or lambda function) which have a body (defined 

with dummy variables) but have no name: 

f = Lambda(x, exp(x)*x) 

f = Lambda((x, y), exp(x)*y) 

The fourth type of functions are composites, like (sin + cos)(x); these work in 

SymPy core, but are not yet part of SymPy. 

 

Examples 

======== 

 

>>> import sympy 

>>> f = sympy.Function("f") 

>>> from sympy.abc import x 

>>> f(x) 

f(x) 

>>> print(sympy.srepr(f(x).func)) 

Function('f') 

>>> f(x).args 

(x,) 

 

""" 

from __future__ import print_function, division 

 

from .add import Add 

from .assumptions import ManagedProperties 

from .basic import Basic 

from .cache import cacheit 

from .compatibility import iterable, is_sequence, as_int, ordered 

from .core import BasicMeta 

from .decorators import _sympifyit 

from .expr import Expr, AtomicExpr 

from .numbers import Rational, Float 

from .operations import LatticeOp 

from .rules import Transform 

from .singleton import S 

from .sympify import sympify 

 

from sympy.core.containers import Tuple, Dict 

from sympy.core.logic import fuzzy_and 

from sympy.core.compatibility import string_types, with_metaclass, range 

from sympy.utilities import default_sort_key 

from sympy.utilities.misc import filldedent 

from sympy.utilities.iterables import uniq 

from sympy.core.evaluate import global_evaluate 

 

import sys 

 

import mpmath 

import mpmath.libmp as mlib 

 

import inspect 

import collections 

 

def _coeff_isneg(a): 

"""Return True if the leading Number is negative. 

 

Examples 

======== 

 

>>> from sympy.core.function import _coeff_isneg 

>>> from sympy import S, Symbol, oo, pi 

>>> _coeff_isneg(-3*pi) 

True 

>>> _coeff_isneg(S(3)) 

False 

>>> _coeff_isneg(-oo) 

True 

>>> _coeff_isneg(Symbol('n', negative=True)) # coeff is 1 

False 

 

""" 

 

if a.is_Mul: 

a = a.args[0] 

return a.is_Number and a.is_negative 

 

 

class PoleError(Exception): 

pass 

 

 

class ArgumentIndexError(ValueError): 

def __str__(self): 

return ("Invalid operation with argument number %s for Function %s" % 

(self.args[1], self.args[0])) 

 

def _getnargs(cls): 

if hasattr(cls, 'eval'): 

if sys.version_info < (3, ): 

return _getnargs_old(cls.eval) 

else: 

return _getnargs_new(cls.eval) 

else: 

return None 

 

def _getnargs_old(eval_): 

evalargspec = inspect.getargspec(eval_) 

if evalargspec.varargs: 

return None 

else: 

evalargs = len(evalargspec.args) - 1 # subtract 1 for cls 

if evalargspec.defaults: 

# if there are default args then they are optional; the 

# fewest args will occur when all defaults are used and 

# the most when none are used (i.e. all args are given) 

return tuple(range( 

evalargs - len(evalargspec.defaults), evalargs + 1)) 

 

return evalargs 

 

def _getnargs_new(eval_): 

parameters = inspect.signature(eval_).parameters.items() 

if [p for n,p in parameters if p.kind == p.VAR_POSITIONAL]: 

return None 

else: 

p_or_k = [p for n,p in parameters if p.kind == p.POSITIONAL_OR_KEYWORD] 

num_no_default = len(list(filter(lambda p:p.default == p.empty, p_or_k))) 

num_with_default = len(list(filter(lambda p:p.default != p.empty, p_or_k))) 

if not num_with_default: 

return num_no_default 

return tuple(range(num_no_default, num_no_default+num_with_default+1)) 

 

 

 

 

class FunctionClass(ManagedProperties): 

""" 

Base class for function classes. FunctionClass is a subclass of type. 

 

Use Function('<function name>' [ , signature ]) to create 

undefined function classes. 

""" 

_new = type.__new__ 

 

def __init__(cls, *args, **kwargs): 

# honor kwarg value or class-defined value before using 

# the number of arguments in the eval function (if present) 

nargs = kwargs.pop('nargs', cls.__dict__.get('nargs', _getnargs(cls))) 

super(FunctionClass, cls).__init__(args, kwargs) 

 

# Canonicalize nargs here; change to set in nargs. 

if is_sequence(nargs): 

if not nargs: 

raise ValueError(filldedent(''' 

Incorrectly specified nargs as %s: 

if there are no arguments, it should be 

`nargs = 0`; 

if there are any number of arguments, 

it should be 

`nargs = None`''' % str(nargs))) 

nargs = tuple(ordered(set(nargs))) 

elif nargs is not None: 

nargs = (as_int(nargs),) 

cls._nargs = nargs 

 

@property 

def __signature__(self): 

""" 

Allow Python 3's inspect.signature to give a useful signature for 

Function subclasses. 

""" 

# Python 3 only, but backports (like the one in IPython) still might 

# call this. 

try: 

from inspect import signature 

except ImportError: 

return None 

 

# TODO: Look at nargs 

return signature(self.eval) 

 

@property 

def nargs(self): 

"""Return a set of the allowed number of arguments for the function. 

 

Examples 

======== 

 

>>> from sympy.core.function import Function 

>>> from sympy.abc import x, y 

>>> f = Function('f') 

 

If the function can take any number of arguments, the set of whole 

numbers is returned: 

 

>>> Function('f').nargs 

Naturals0() 

 

If the function was initialized to accept one or more arguments, a 

corresponding set will be returned: 

 

>>> Function('f', nargs=1).nargs 

{1} 

>>> Function('f', nargs=(2, 1)).nargs 

{1, 2} 

 

The undefined function, after application, also has the nargs 

attribute; the actual number of arguments is always available by 

checking the ``args`` attribute: 

 

>>> f = Function('f') 

>>> f(1).nargs 

Naturals0() 

>>> len(f(1).args) 

1 

""" 

from sympy.sets.sets import FiniteSet 

# XXX it would be nice to handle this in __init__ but there are import 

# problems with trying to import FiniteSet there 

return FiniteSet(*self._nargs) if self._nargs else S.Naturals0 

 

def __repr__(cls): 

return cls.__name__ 

 

 

class Application(with_metaclass(FunctionClass, Basic)): 

""" 

Base class for applied functions. 

 

Instances of Application represent the result of applying an application of 

any type to any object. 

""" 

 

is_Function = True 

 

@cacheit 

def __new__(cls, *args, **options): 

from sympy.sets.fancysets import Naturals0 

from sympy.sets.sets import FiniteSet 

 

args = list(map(sympify, args)) 

evaluate = options.pop('evaluate', global_evaluate[0]) 

# WildFunction (and anything else like it) may have nargs defined 

# and we throw that value away here 

options.pop('nargs', None) 

 

if options: 

raise ValueError("Unknown options: %s" % options) 

 

if evaluate: 

evaluated = cls.eval(*args) 

if evaluated is not None: 

return evaluated 

 

obj = super(Application, cls).__new__(cls, *args, **options) 

 

# make nargs uniform here 

try: 

# things passing through here: 

# - functions subclassed from Function (e.g. myfunc(1).nargs) 

# - functions like cos(1).nargs 

# - AppliedUndef with given nargs like Function('f', nargs=1)(1).nargs 

# Canonicalize nargs here 

if is_sequence(obj.nargs): 

nargs = tuple(ordered(set(obj.nargs))) 

elif obj.nargs is not None: 

nargs = (as_int(obj.nargs),) 

else: 

nargs = None 

except AttributeError: 

# things passing through here: 

# - WildFunction('f').nargs 

# - AppliedUndef with no nargs like Function('f')(1).nargs 

nargs = obj._nargs # note the underscore here 

# convert to FiniteSet 

obj.nargs = FiniteSet(*nargs) if nargs else Naturals0() 

return obj 

 

@classmethod 

def eval(cls, *args): 

""" 

Returns a canonical form of cls applied to arguments args. 

 

The eval() method is called when the class cls is about to be 

instantiated and it should return either some simplified instance 

(possible of some other class), or if the class cls should be 

unmodified, return None. 

 

Examples of eval() for the function "sign" 

--------------------------------------------- 

 

@classmethod 

def eval(cls, arg): 

if arg is S.NaN: 

return S.NaN 

if arg is S.Zero: return S.Zero 

if arg.is_positive: return S.One 

if arg.is_negative: return S.NegativeOne 

if isinstance(arg, Mul): 

coeff, terms = arg.as_coeff_Mul(rational=True) 

if coeff is not S.One: 

return cls(coeff) * cls(terms) 

 

""" 

return 

 

@property 

def func(self): 

return self.__class__ 

 

def _eval_subs(self, old, new): 

if (old.is_Function and new.is_Function and old == self.func and 

len(self.args) in new.nargs): 

return new(*self.args) 

 

 

class Function(Application, Expr): 

"""Base class for applied mathematical functions. 

 

It also serves as a constructor for undefined function classes. 

 

Examples 

======== 

 

First example shows how to use Function as a constructor for undefined 

function classes: 

 

>>> from sympy import Function, Symbol 

>>> x = Symbol('x') 

>>> f = Function('f') 

>>> g = Function('g')(x) 

>>> f 

f 

>>> f(x) 

f(x) 

>>> g 

g(x) 

>>> f(x).diff(x) 

Derivative(f(x), x) 

>>> g.diff(x) 

Derivative(g(x), x) 

 

In the following example Function is used as a base class for 

``my_func`` that represents a mathematical function *my_func*. Suppose 

that it is well known, that *my_func(0)* is *1* and *my_func* at infinity 

goes to *0*, so we want those two simplifications to occur automatically. 

Suppose also that *my_func(x)* is real exactly when *x* is real. Here is 

an implementation that honours those requirements: 

 

>>> from sympy import Function, S, oo, I, sin 

>>> class my_func(Function): 

... 

... @classmethod 

... def eval(cls, x): 

... if x.is_Number: 

... if x is S.Zero: 

... return S.One 

... elif x is S.Infinity: 

... return S.Zero 

... 

... def _eval_is_real(self): 

... return self.args[0].is_real 

... 

>>> x = S('x') 

>>> my_func(0) + sin(0) 

1 

>>> my_func(oo) 

0 

>>> my_func(3.54).n() # Not yet implemented for my_func. 

my_func(3.54) 

>>> my_func(I).is_real 

False 

 

In order for ``my_func`` to become useful, several other methods would 

need to be implemented. See source code of some of the already 

implemented functions for more complete examples. 

 

Also, if the function can take more than one argument, then ``nargs`` 

must be defined, e.g. if ``my_func`` can take one or two arguments 

then, 

 

>>> class my_func(Function): 

... nargs = (1, 2) 

... 

>>> 

""" 

 

@property 

def _diff_wrt(self): 

"""Allow derivatives wrt functions. 

 

Examples 

======== 

 

>>> from sympy import Function, Symbol 

>>> f = Function('f') 

>>> x = Symbol('x') 

>>> f(x)._diff_wrt 

True 

 

""" 

return True 

 

@cacheit 

def __new__(cls, *args, **options): 

# Handle calls like Function('f') 

if cls is Function: 

return UndefinedFunction(*args, **options) 

 

n = len(args) 

if n not in cls.nargs: 

# XXX: exception message must be in exactly this format to 

# make it work with NumPy's functions like vectorize(). See, 

# for example, https://github.com/numpy/numpy/issues/1697. 

# The ideal solution would be just to attach metadata to 

# the exception and change NumPy to take advantage of this. 

temp = ('%(name)s takes %(qual)s %(args)s ' 

'argument%(plural)s (%(given)s given)') 

raise TypeError(temp % { 

'name': cls, 

'qual': 'exactly' if len(cls.nargs) == 1 else 'at least', 

'args': min(cls.nargs), 

'plural': 's'*(min(cls.nargs) != 1), 

'given': n}) 

 

evaluate = options.get('evaluate', global_evaluate[0]) 

result = super(Function, cls).__new__(cls, *args, **options) 

if not evaluate or not isinstance(result, cls): 

return result 

 

pr = max(cls._should_evalf(a) for a in result.args) 

pr2 = min(cls._should_evalf(a) for a in result.args) 

if pr2 > 0: 

return result.evalf(mlib.libmpf.prec_to_dps(pr)) 

return result 

 

@classmethod 

def _should_evalf(cls, arg): 

""" 

Decide if the function should automatically evalf(). 

 

By default (in this implementation), this happens if (and only if) the 

ARG is a floating point number. 

This function is used by __new__. 

 

Returns the precision to evalf to, or -1 if it shouldn't evalf. 

""" 

from sympy.core.symbol import Wild 

if arg.is_Float: 

return arg._prec 

if not arg.is_Add: 

return -1 

# Don't use as_real_imag() here, that's too much work 

a, b = Wild('a'), Wild('b') 

m = arg.match(a + b*S.ImaginaryUnit) 

if not m or not (m[a].is_Float or m[b].is_Float): 

return -1 

l = [m[i]._prec for i in m if m[i].is_Float] 

l.append(-1) 

return max(l) 

 

@classmethod 

def class_key(cls): 

from sympy.sets.fancysets import Naturals0 

funcs = { 

'exp': 10, 

'log': 11, 

'sin': 20, 

'cos': 21, 

'tan': 22, 

'cot': 23, 

'sinh': 30, 

'cosh': 31, 

'tanh': 32, 

'coth': 33, 

'conjugate': 40, 

're': 41, 

'im': 42, 

'arg': 43, 

} 

name = cls.__name__ 

 

try: 

i = funcs[name] 

except KeyError: 

i = 0 if isinstance(cls.nargs, Naturals0) else 10000 

 

return 4, i, name 

 

@property 

def is_commutative(self): 

""" 

Returns whether the functon is commutative. 

""" 

if all(getattr(t, 'is_commutative') for t in self.args): 

return True 

else: 

return False 

 

def _eval_evalf(self, prec): 

# Lookup mpmath function based on name 

fname = self.func.__name__ 

try: 

if not hasattr(mpmath, fname): 

from sympy.utilities.lambdify import MPMATH_TRANSLATIONS 

fname = MPMATH_TRANSLATIONS[fname] 

func = getattr(mpmath, fname) 

except (AttributeError, KeyError): 

try: 

return Float(self._imp_(*self.args), prec) 

except (AttributeError, TypeError, ValueError): 

return 

 

# Convert all args to mpf or mpc 

# Convert the arguments to *higher* precision than requested for the 

# final result. 

# XXX + 5 is a guess, it is similar to what is used in evalf.py. Should 

# we be more intelligent about it? 

try: 

args = [arg._to_mpmath(prec + 5) for arg in self.args] 

def bad(m): 

from mpmath import mpf, mpc 

# the precision of an mpf value is the last element 

# if that is 1 (and m[1] is not 1 which would indicate a 

# power of 2), then the eval failed; so check that none of 

# the arguments failed to compute to a finite precision. 

# Note: An mpc value has two parts, the re and imag tuple; 

# check each of those parts, too. Anything else is allowed to 

# pass 

if isinstance(m, mpf): 

m = m._mpf_ 

return m[1] !=1 and m[-1] == 1 

elif isinstance(m, mpc): 

m, n = m._mpc_ 

return m[1] !=1 and m[-1] == 1 and \ 

n[1] !=1 and n[-1] == 1 

else: 

return False 

if any(bad(a) for a in args): 

raise ValueError # one or more args failed to compute with significance 

except ValueError: 

return 

 

with mpmath.workprec(prec): 

v = func(*args) 

 

return Expr._from_mpmath(v, prec) 

 

def _eval_derivative(self, s): 

# f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s) 

i = 0 

l = [] 

for a in self.args: 

i += 1 

da = a.diff(s) 

if da is S.Zero: 

continue 

try: 

df = self.fdiff(i) 

except ArgumentIndexError: 

df = Function.fdiff(self, i) 

l.append(df * da) 

return Add(*l) 

 

def _eval_is_commutative(self): 

return fuzzy_and(a.is_commutative for a in self.args) 

 

def _eval_is_complex(self): 

return fuzzy_and(a.is_complex for a in self.args) 

 

def as_base_exp(self): 

""" 

Returns the method as the 2-tuple (base, exponent). 

""" 

return self, S.One 

 

def _eval_aseries(self, n, args0, x, logx): 

""" 

Compute an asymptotic expansion around args0, in terms of self.args. 

This function is only used internally by _eval_nseries and should not 

be called directly; derived classes can overwrite this to implement 

asymptotic expansions. 

""" 

from sympy.utilities.misc import filldedent 

raise PoleError(filldedent(''' 

Asymptotic expansion of %s around %s is 

not implemented.''' % (type(self), args0))) 

 

def _eval_nseries(self, x, n, logx): 

""" 

This function does compute series for multivariate functions, 

but the expansion is always in terms of *one* variable. 

Examples 

======== 

 

>>> from sympy import atan2 

>>> from sympy.abc import x, y 

>>> atan2(x, y).series(x, n=2) 

atan2(0, y) + x/y + O(x**2) 

>>> atan2(x, y).series(y, n=2) 

-y/x + atan2(x, 0) + O(y**2) 

 

This function also computes asymptotic expansions, if necessary 

and possible: 

 

>>> from sympy import loggamma 

>>> loggamma(1/x)._eval_nseries(x,0,None) 

-1/x - log(x)/x + log(x)/2 + O(1) 

 

""" 

from sympy import Order 

from sympy.sets.sets import FiniteSet 

args = self.args 

args0 = [t.limit(x, 0) for t in args] 

if any(t.is_finite is False for t in args0): 

from sympy import oo, zoo, nan 

# XXX could use t.as_leading_term(x) here but it's a little 

# slower 

a = [t.compute_leading_term(x, logx=logx) for t in args] 

a0 = [t.limit(x, 0) for t in a] 

if any([t.has(oo, -oo, zoo, nan) for t in a0]): 

return self._eval_aseries(n, args0, x, logx) 

# Careful: the argument goes to oo, but only logarithmically so. We 

# are supposed to do a power series expansion "around the 

# logarithmic term". e.g. 

# f(1+x+log(x)) 

# -> f(1+logx) + x*f'(1+logx) + O(x**2) 

# where 'logx' is given in the argument 

a = [t._eval_nseries(x, n, logx) for t in args] 

z = [r - r0 for (r, r0) in zip(a, a0)] 

p = [Dummy() for t in z] 

q = [] 

v = None 

for ai, zi, pi in zip(a0, z, p): 

if zi.has(x): 

if v is not None: 

raise NotImplementedError 

q.append(ai + pi) 

v = pi 

else: 

q.append(ai) 

e1 = self.func(*q) 

if v is None: 

return e1 

s = e1._eval_nseries(v, n, logx) 

o = s.getO() 

s = s.removeO() 

s = s.subs(v, zi).expand() + Order(o.expr.subs(v, zi), x) 

return s 

if (self.func.nargs is S.Naturals0 

or (self.func.nargs == FiniteSet(1) and args0[0]) 

or any(c > 1 for c in self.func.nargs)): 

e = self 

e1 = e.expand() 

if e == e1: 

#for example when e = sin(x+1) or e = sin(cos(x)) 

#let's try the general algorithm 

term = e.subs(x, S.Zero) 

if term.is_finite is False or term is S.NaN: 

raise PoleError("Cannot expand %s around 0" % (self)) 

series = term 

fact = S.One 

_x = Dummy('x') 

e = e.subs(x, _x) 

for i in range(n - 1): 

i += 1 

fact *= Rational(i) 

e = e.diff(_x) 

subs = e.subs(_x, S.Zero) 

if subs is S.NaN: 

# try to evaluate a limit if we have to 

subs = e.limit(_x, S.Zero) 

if subs.is_finite is False: 

raise PoleError("Cannot expand %s around 0" % (self)) 

term = subs*(x**i)/fact 

term = term.expand() 

series += term 

return series + Order(x**n, x) 

return e1.nseries(x, n=n, logx=logx) 

arg = self.args[0] 

l = [] 

g = None 

# try to predict a number of terms needed 

nterms = n + 2 

cf = Order(arg.as_leading_term(x), x).getn() 

if cf != 0: 

nterms = int(nterms / cf) 

for i in range(nterms): 

g = self.taylor_term(i, arg, g) 

g = g.nseries(x, n=n, logx=logx) 

l.append(g) 

return Add(*l) + Order(x**n, x) 

 

def fdiff(self, argindex=1): 

""" 

Returns the first derivative of the function. 

""" 

if not (1 <= argindex <= len(self.args)): 

raise ArgumentIndexError(self, argindex) 

 

if self.args[argindex - 1].is_Symbol: 

for i in range(len(self.args)): 

if i == argindex - 1: 

continue 

# See issue 8510 

if self.args[argindex - 1] in self.args[i].free_symbols: 

break 

else: 

return Derivative(self, self.args[argindex - 1], evaluate=False) 

# See issue 4624 and issue 4719 and issue 5600 

arg_dummy = Dummy('xi_%i' % argindex) 

arg_dummy.dummy_index = hash(self.args[argindex - 1]) 

new_args = [arg for arg in self.args] 

new_args[argindex-1] = arg_dummy 

return Subs(Derivative(self.func(*new_args), arg_dummy), 

arg_dummy, self.args[argindex - 1]) 

 

def _eval_as_leading_term(self, x): 

"""Stub that should be overridden by new Functions to return 

the first non-zero term in a series if ever an x-dependent 

argument whose leading term vanishes as x -> 0 might be encountered. 

See, for example, cos._eval_as_leading_term. 

""" 

from sympy import Order 

args = [a.as_leading_term(x) for a in self.args] 

o = Order(1, x) 

if any(x in a.free_symbols and o.contains(a) for a in args): 

# Whereas x and any finite number are contained in O(1, x), 

# expressions like 1/x are not. If any arg simplified to a 

# vanishing expression as x -> 0 (like x or x**2, but not 

# 3, 1/x, etc...) then the _eval_as_leading_term is needed 

# to supply the first non-zero term of the series, 

# 

# e.g. expression leading term 

# ---------- ------------ 

# cos(1/x) cos(1/x) 

# cos(cos(x)) cos(1) 

# cos(x) 1 <- _eval_as_leading_term needed 

# sin(x) x <- _eval_as_leading_term needed 

# 

raise NotImplementedError( 

'%s has no _eval_as_leading_term routine' % self.func) 

else: 

return self.func(*args) 

 

def _sage_(self): 

import sage.all as sage 

fname = self.func.__name__ 

func = getattr(sage, fname) 

args = [arg._sage_() for arg in self.args] 

return func(*args) 

 

 

class AppliedUndef(Function): 

""" 

Base class for expressions resulting from the application of an undefined 

function. 

""" 

 

def __new__(cls, *args, **options): 

args = list(map(sympify, args)) 

obj = super(AppliedUndef, cls).__new__(cls, *args, **options) 

return obj 

 

def _eval_as_leading_term(self, x): 

return self 

 

def _sage_(self): 

import sage.all as sage 

fname = str(self.func) 

args = [arg._sage_() for arg in self.args] 

func = sage.function(fname)(*args) 

return func 

 

class UndefinedFunction(FunctionClass): 

""" 

The (meta)class of undefined functions. 

""" 

def __new__(mcl, name, **kwargs): 

ret = BasicMeta.__new__(mcl, name, (AppliedUndef,), kwargs) 

ret.__module__ = None 

return ret 

 

def __instancecheck__(cls, instance): 

return cls in type(instance).__mro__ 

 

UndefinedFunction.__eq__ = lambda s, o: (isinstance(o, s.__class__) and 

(s.class_key() == o.class_key())) 

 

class WildFunction(Function, AtomicExpr): 

""" 

A WildFunction function matches any function (with its arguments). 

 

Examples 

======== 

 

>>> from sympy import WildFunction, Function, cos 

>>> from sympy.abc import x, y 

>>> F = WildFunction('F') 

>>> f = Function('f') 

>>> F.nargs 

Naturals0() 

>>> x.match(F) 

>>> F.match(F) 

{F_: F_} 

>>> f(x).match(F) 

{F_: f(x)} 

>>> cos(x).match(F) 

{F_: cos(x)} 

>>> f(x, y).match(F) 

{F_: f(x, y)} 

 

To match functions with a given number of arguments, set ``nargs`` to the 

desired value at instantiation: 

 

>>> F = WildFunction('F', nargs=2) 

>>> F.nargs 

{2} 

>>> f(x).match(F) 

>>> f(x, y).match(F) 

{F_: f(x, y)} 

 

To match functions with a range of arguments, set ``nargs`` to a tuple 

containing the desired number of arguments, e.g. if ``nargs = (1, 2)`` 

then functions with 1 or 2 arguments will be matched. 

 

>>> F = WildFunction('F', nargs=(1, 2)) 

>>> F.nargs 

{1, 2} 

>>> f(x).match(F) 

{F_: f(x)} 

>>> f(x, y).match(F) 

{F_: f(x, y)} 

>>> f(x, y, 1).match(F) 

 

""" 

 

include = set() 

 

def __init__(cls, name, **assumptions): 

from sympy.sets.sets import Set, FiniteSet 

cls.name = name 

nargs = assumptions.pop('nargs', S.Naturals0) 

if not isinstance(nargs, Set): 

# Canonicalize nargs here. See also FunctionClass. 

if is_sequence(nargs): 

nargs = tuple(ordered(set(nargs))) 

elif nargs is not None: 

nargs = (as_int(nargs),) 

nargs = FiniteSet(*nargs) 

cls.nargs = nargs 

 

def matches(self, expr, repl_dict={}, old=False): 

if not isinstance(expr, (AppliedUndef, Function)): 

return None 

if len(expr.args) not in self.nargs: 

return None 

 

repl_dict = repl_dict.copy() 

repl_dict[self] = expr 

return repl_dict 

 

 

class Derivative(Expr): 

""" 

Carries out differentiation of the given expression with respect to symbols. 

 

expr must define ._eval_derivative(symbol) method that returns 

the differentiation result. This function only needs to consider the 

non-trivial case where expr contains symbol and it should call the diff() 

method internally (not _eval_derivative); Derivative should be the only 

one to call _eval_derivative. 

 

Simplification of high-order derivatives: 

 

Because there can be a significant amount of simplification that can be 

done when multiple differentiations are performed, results will be 

automatically simplified in a fairly conservative fashion unless the 

keyword ``simplify`` is set to False. 

 

>>> from sympy import sqrt, diff 

>>> from sympy.abc import x 

>>> e = sqrt((x + 1)**2 + x) 

>>> diff(e, x, 5, simplify=False).count_ops() 

136 

>>> diff(e, x, 5).count_ops() 

30 

 

Ordering of variables: 

 

If evaluate is set to True and the expression can not be evaluated, the 

list of differentiation symbols will be sorted, that is, the expression is 

assumed to have continuous derivatives up to the order asked. This sorting 

assumes that derivatives wrt Symbols commute, derivatives wrt non-Symbols 

commute, but Symbol and non-Symbol derivatives don't commute with each 

other. 

 

Derivative wrt non-Symbols: 

 

This class also allows derivatives wrt non-Symbols that have _diff_wrt 

set to True, such as Function and Derivative. When a derivative wrt a non- 

Symbol is attempted, the non-Symbol is temporarily converted to a Symbol 

while the differentiation is performed. 

 

Note that this may seem strange, that Derivative allows things like 

f(g(x)).diff(g(x)), or even f(cos(x)).diff(cos(x)). The motivation for 

allowing this syntax is to make it easier to work with variational calculus 

(i.e., the Euler-Lagrange method). The best way to understand this is that 

the action of derivative with respect to a non-Symbol is defined by the 

above description: the object is substituted for a Symbol and the 

derivative is taken with respect to that. This action is only allowed for 

objects for which this can be done unambiguously, for example Function and 

Derivative objects. Note that this leads to what may appear to be 

mathematically inconsistent results. For example:: 

 

>>> from sympy import cos, sin, sqrt 

>>> from sympy.abc import x 

>>> (2*cos(x)).diff(cos(x)) 

2 

>>> (2*sqrt(1 - sin(x)**2)).diff(cos(x)) 

0 

 

This appears wrong because in fact 2*cos(x) and 2*sqrt(1 - sin(x)**2) are 

identically equal. However this is the wrong way to think of this. Think 

of it instead as if we have something like this:: 

 

>>> from sympy.abc import c, s 

>>> def F(u): 

... return 2*u 

... 

>>> def G(u): 

... return 2*sqrt(1 - u**2) 

... 

>>> F(cos(x)) 

2*cos(x) 

>>> G(sin(x)) 

2*sqrt(-sin(x)**2 + 1) 

>>> F(c).diff(c) 

2 

>>> F(c).diff(c) 

2 

>>> G(s).diff(c) 

0 

>>> G(sin(x)).diff(cos(x)) 

0 

 

Here, the Symbols c and s act just like the functions cos(x) and sin(x), 

respectively. Think of 2*cos(x) as f(c).subs(c, cos(x)) (or f(c) *at* 

c = cos(x)) and 2*sqrt(1 - sin(x)**2) as g(s).subs(s, sin(x)) (or g(s) *at* 

s = sin(x)), where f(u) == 2*u and g(u) == 2*sqrt(1 - u**2). Here, we 

define the function first and evaluate it at the function, but we can 

actually unambiguously do this in reverse in SymPy, because 

expr.subs(Function, Symbol) is well-defined: just structurally replace the 

function everywhere it appears in the expression. 

 

This is the same notational convenience used in the Euler-Lagrange method 

when one says F(t, f(t), f'(t)).diff(f(t)). What is actually meant is 

that the expression in question is represented by some F(t, u, v) at u = 

f(t) and v = f'(t), and F(t, f(t), f'(t)).diff(f(t)) simply means F(t, u, 

v).diff(u) at u = f(t). 

 

We do not allow derivatives to be taken with respect to expressions where this 

is not so well defined. For example, we do not allow expr.diff(x*y) 

because there are multiple ways of structurally defining where x*y appears 

in an expression, some of which may surprise the reader (for example, a 

very strict definition would have that (x*y*z).diff(x*y) == 0). 

 

>>> from sympy.abc import x, y, z 

>>> (x*y*z).diff(x*y) 

Traceback (most recent call last): 

... 

ValueError: Can't differentiate wrt the variable: x*y, 1 

 

Note that this definition also fits in nicely with the definition of the 

chain rule. Note how the chain rule in SymPy is defined using unevaluated 

Subs objects:: 

 

>>> from sympy import symbols, Function 

>>> f, g = symbols('f g', cls=Function) 

>>> f(2*g(x)).diff(x) 

2*Derivative(g(x), x)*Subs(Derivative(f(_xi_1), _xi_1), 

(_xi_1,), (2*g(x),)) 

>>> f(g(x)).diff(x) 

Derivative(g(x), x)*Subs(Derivative(f(_xi_1), _xi_1), 

(_xi_1,), (g(x),)) 

 

Finally, note that, to be consistent with variational calculus, and to 

ensure that the definition of substituting a Function for a Symbol in an 

expression is well-defined, derivatives of functions are assumed to not be 

related to the function. In other words, we have:: 

 

>>> from sympy import diff 

>>> diff(f(x), x).diff(f(x)) 

0 

 

The same is true for derivatives of different orders:: 

 

>>> diff(f(x), x, 2).diff(diff(f(x), x, 1)) 

0 

>>> diff(f(x), x, 1).diff(diff(f(x), x, 2)) 

0 

 

Note, any class can allow derivatives to be taken with respect to itself. 

See the docstring of Expr._diff_wrt. 

 

Examples 

======== 

 

Some basic examples: 

 

>>> from sympy import Derivative, Symbol, Function 

>>> f = Function('f') 

>>> g = Function('g') 

>>> x = Symbol('x') 

>>> y = Symbol('y') 

 

>>> Derivative(x**2, x, evaluate=True) 

2*x 

>>> Derivative(Derivative(f(x,y), x), y) 

Derivative(f(x, y), x, y) 

>>> Derivative(f(x), x, 3) 

Derivative(f(x), x, x, x) 

>>> Derivative(f(x, y), y, x, evaluate=True) 

Derivative(f(x, y), x, y) 

 

Now some derivatives wrt functions: 

 

>>> Derivative(f(x)**2, f(x), evaluate=True) 

2*f(x) 

>>> Derivative(f(g(x)), x, evaluate=True) 

Derivative(g(x), x)*Subs(Derivative(f(_xi_1), _xi_1), 

(_xi_1,), (g(x),)) 

 

""" 

 

is_Derivative = True 

 

@property 

def _diff_wrt(self): 

"""Allow derivatives wrt Derivatives if it contains a function. 

 

Examples 

======== 

 

>>> from sympy import Function, Symbol, Derivative 

>>> f = Function('f') 

>>> x = Symbol('x') 

>>> Derivative(f(x),x)._diff_wrt 

True 

>>> Derivative(x**2,x)._diff_wrt 

False 

""" 

if self.expr.is_Function: 

return True 

else: 

return False 

 

def __new__(cls, expr, *variables, **assumptions): 

 

expr = sympify(expr) 

 

# There are no variables, we differentiate wrt all of the free symbols 

# in expr. 

if not variables: 

variables = expr.free_symbols 

if len(variables) != 1: 

if expr.is_number: 

return S.Zero 

from sympy.utilities.misc import filldedent 

if len(variables) == 0: 

raise ValueError(filldedent(''' 

Since there are no variables in the expression, 

the variable(s) of differentiation must be supplied 

to differentiate %s''' % expr)) 

else: 

raise ValueError(filldedent(''' 

Since there is more than one variable in the 

expression, the variable(s) of differentiation 

must be supplied to differentiate %s''' % expr)) 

 

# Standardize the variables by sympifying them and making appending a 

# count of 1 if there is only one variable: diff(e,x)->diff(e,x,1). 

variables = list(sympify(variables)) 

if not variables[-1].is_Integer or len(variables) == 1: 

variables.append(S.One) 

 

# Split the list of variables into a list of the variables we are diff 

# wrt, where each element of the list has the form (s, count) where 

# s is the entity to diff wrt and count is the order of the 

# derivative. 

variable_count = [] 

all_zero = True 

i = 0 

while i < len(variables) - 1: # process up to final Integer 

v, count = variables[i: i + 2] 

iwas = i 

if v._diff_wrt: 

# We need to test the more specific case of count being an 

# Integer first. 

if count.is_Integer: 

count = int(count) 

i += 2 

elif count._diff_wrt: 

count = 1 

i += 1 

 

if i == iwas: # didn't get an update because of bad input 

from sympy.utilities.misc import filldedent 

last_digit = int(str(count)[-1]) 

ordinal = 'st' if last_digit == 1 else 'nd' if last_digit == 2 else 'rd' if last_digit == 3 else 'th' 

raise ValueError(filldedent(''' 

Can\'t calculate %s%s derivative wrt %s.''' % (count, ordinal, v))) 

 

if all_zero and not count == 0: 

all_zero = False 

 

if count: 

variable_count.append((v, count)) 

 

# We make a special case for 0th derivative, because there is no 

# good way to unambiguously print this. 

if all_zero: 

return expr 

 

# Pop evaluate because it is not really an assumption and we will need 

# to track it carefully below. 

evaluate = assumptions.pop('evaluate', False) 

 

# Look for a quick exit if there are symbols that don't appear in 

# expression at all. Note, this cannnot check non-symbols like 

# functions and Derivatives as those can be created by intermediate 

# derivatives. 

if evaluate: 

from sympy import IndexedBase 

symbol_set = set(sc[0].base if sc[0].is_Indexed else sc[0] for sc in variable_count if sc[0].is_Symbol) 

if symbol_set.difference(expr.free_symbols).difference(expr.atoms(IndexedBase)): 

return S.Zero 

 

# We make a generator so as to only generate a variable when necessary. 

# If a high order of derivative is requested and the expr becomes 0 

# after a few differentiations, then we won't need the other variables. 

variablegen = (v for v, count in variable_count for i in range(count)) 

 

# If we can't compute the derivative of expr (but we wanted to) and 

# expr is itself not a Derivative, finish building an unevaluated 

# derivative class by calling Expr.__new__. 

if (not (hasattr(expr, '_eval_derivative') and evaluate) and 

(not isinstance(expr, Derivative))): 

variables = list(variablegen) 

# If we wanted to evaluate, we sort the variables into standard 

# order for later comparisons. This is too aggressive if evaluate 

# is False, so we don't do it in that case. 

if evaluate: 

#TODO: check if assumption of discontinuous derivatives exist 

variables = cls._sort_variables(variables) 

# Here we *don't* need to reinject evaluate into assumptions 

# because we are done with it and it is not an assumption that 

# Expr knows about. 

obj = Expr.__new__(cls, expr, *variables, **assumptions) 

return obj 

 

# Compute the derivative now by repeatedly calling the 

# _eval_derivative method of expr for each variable. When this method 

# returns None, the derivative couldn't be computed wrt that variable 

# and we save the variable for later. 

unhandled_variables = [] 

 

# Once we encouter a non_symbol that is unhandled, we stop taking 

# derivatives entirely. This is because derivatives wrt functions 

# don't commute with derivatives wrt symbols and we can't safely 

# continue. 

unhandled_non_symbol = False 

nderivs = 0 # how many derivatives were performed 

for v in variablegen: 

is_symbol = v.is_Symbol 

 

if unhandled_non_symbol: 

obj = None 

else: 

if not is_symbol: 

new_v = Dummy('xi_%i' % i) 

new_v.dummy_index = hash(v) 

expr = expr.xreplace({v: new_v}) 

old_v = v 

v = new_v 

obj = expr._eval_derivative(v) 

nderivs += 1 

if not is_symbol: 

if obj is not None: 

if not old_v.is_Symbol and obj.is_Derivative: 

# Derivative evaluated at a point that is not a 

# symbol 

obj = Subs(obj, v, old_v) 

else: 

obj = obj.xreplace({v: old_v}) 

v = old_v 

 

if obj is None: 

unhandled_variables.append(v) 

if not is_symbol: 

unhandled_non_symbol = True 

elif obj is S.Zero: 

return S.Zero 

else: 

expr = obj 

 

if unhandled_variables: 

unhandled_variables = cls._sort_variables(unhandled_variables) 

expr = Expr.__new__(cls, expr, *unhandled_variables, **assumptions) 

else: 

# We got a Derivative at the end of it all, and we rebuild it by 

# sorting its variables. 

if isinstance(expr, Derivative): 

expr = cls( 

expr.args[0], *cls._sort_variables(expr.args[1:]) 

) 

 

if nderivs > 1 and assumptions.get('simplify', True): 

from sympy.core.exprtools import factor_terms 

from sympy.simplify.simplify import signsimp 

expr = factor_terms(signsimp(expr)) 

return expr 

 

@classmethod 

def _sort_variables(cls, vars): 

"""Sort variables, but disallow sorting of non-symbols. 

 

When taking derivatives, the following rules usually hold: 

 

* Derivative wrt different symbols commute. 

* Derivative wrt different non-symbols commute. 

* Derivatives wrt symbols and non-symbols don't commute. 

 

Examples 

======== 

 

>>> from sympy import Derivative, Function, symbols 

>>> vsort = Derivative._sort_variables 

>>> x, y, z = symbols('x y z') 

>>> f, g, h = symbols('f g h', cls=Function) 

 

>>> vsort((x,y,z)) 

[x, y, z] 

 

>>> vsort((h(x),g(x),f(x))) 

[f(x), g(x), h(x)] 

 

>>> vsort((z,y,x,h(x),g(x),f(x))) 

[x, y, z, f(x), g(x), h(x)] 

 

>>> vsort((x,f(x),y,f(y))) 

[x, f(x), y, f(y)] 

 

>>> vsort((y,x,g(x),f(x),z,h(x),y,x)) 

[x, y, f(x), g(x), z, h(x), x, y] 

 

>>> vsort((z,y,f(x),x,f(x),g(x))) 

[y, z, f(x), x, f(x), g(x)] 

 

>>> vsort((z,y,f(x),x,f(x),g(x),z,z,y,x)) 

[y, z, f(x), x, f(x), g(x), x, y, z, z] 

""" 

 

sorted_vars = [] 

symbol_part = [] 

non_symbol_part = [] 

for v in vars: 

if not v.is_Symbol: 

if len(symbol_part) > 0: 

sorted_vars.extend(sorted(symbol_part, 

key=default_sort_key)) 

symbol_part = [] 

non_symbol_part.append(v) 

else: 

if len(non_symbol_part) > 0: 

sorted_vars.extend(sorted(non_symbol_part, 

key=default_sort_key)) 

non_symbol_part = [] 

symbol_part.append(v) 

if len(non_symbol_part) > 0: 

sorted_vars.extend(sorted(non_symbol_part, 

key=default_sort_key)) 

if len(symbol_part) > 0: 

sorted_vars.extend(sorted(symbol_part, 

key=default_sort_key)) 

return sorted_vars 

 

def _eval_is_commutative(self): 

return self.expr.is_commutative 

 

def _eval_derivative(self, v): 

# If the variable s we are diff wrt is not in self.variables, we 

# assume that we might be able to take the derivative. 

if v not in self.variables: 

obj = self.expr.diff(v) 

if obj is S.Zero: 

return S.Zero 

if isinstance(obj, Derivative): 

return obj.func(obj.expr, *(self.variables + obj.variables)) 

# The derivative wrt s could have simplified things such that the 

# derivative wrt things in self.variables can now be done. Thus, 

# we set evaluate=True to see if there are any other derivatives 

# that can be done. The most common case is when obj is a simple 

# number so that the derivative wrt anything else will vanish. 

return self.func(obj, *self.variables, evaluate=True) 

# In this case s was in self.variables so the derivatve wrt s has 

# already been attempted and was not computed, either because it 

# couldn't be or evaluate=False originally. 

return self.func(self.expr, *(self.variables + (v, )), evaluate=False) 

 

def doit(self, **hints): 

expr = self.expr 

if hints.get('deep', True): 

expr = expr.doit(**hints) 

hints['evaluate'] = True 

return self.func(expr, *self.variables, **hints) 

 

@_sympifyit('z0', NotImplementedError) 

def doit_numerically(self, z0): 

""" 

Evaluate the derivative at z numerically. 

 

When we can represent derivatives at a point, this should be folded 

into the normal evalf. For now, we need a special method. 

""" 

import mpmath 

from sympy.core.expr import Expr 

if len(self.free_symbols) != 1 or len(self.variables) != 1: 

raise NotImplementedError('partials and higher order derivatives') 

z = list(self.free_symbols)[0] 

 

def eval(x): 

f0 = self.expr.subs(z, Expr._from_mpmath(x, prec=mpmath.mp.prec)) 

f0 = f0.evalf(mlib.libmpf.prec_to_dps(mpmath.mp.prec)) 

return f0._to_mpmath(mpmath.mp.prec) 

return Expr._from_mpmath(mpmath.diff(eval, 

z0._to_mpmath(mpmath.mp.prec)), 

mpmath.mp.prec) 

 

@property 

def expr(self): 

return self._args[0] 

 

@property 

def variables(self): 

return self._args[1:] 

 

@property 

def free_symbols(self): 

return self.expr.free_symbols 

 

def _eval_subs(self, old, new): 

if old in self.variables and not new._diff_wrt: 

# issue 4719 

return Subs(self, old, new) 

# If both are Derivatives with the same expr, check if old is 

# equivalent to self or if old is a subderivative of self. 

if old.is_Derivative and old.expr == self.expr: 

# Check if canonnical order of variables is equal. 

old_vars = collections.Counter(old.variables) 

self_vars = collections.Counter(self.variables) 

if old_vars == self_vars: 

return new 

 

# collections.Counter doesn't have __le__ 

def _subset(a, b): 

return all(a[i] <= b[i] for i in a) 

 

if _subset(old_vars, self_vars): 

return Derivative(new, *(self_vars - old_vars).elements()) 

 

return Derivative(*(x._subs(old, new) for x in self.args)) 

 

def _eval_lseries(self, x, logx): 

dx = self.variables 

for term in self.expr.lseries(x, logx=logx): 

yield self.func(term, *dx) 

 

def _eval_nseries(self, x, n, logx): 

arg = self.expr.nseries(x, n=n, logx=logx) 

o = arg.getO() 

dx = self.variables 

rv = [self.func(a, *dx) for a in Add.make_args(arg.removeO())] 

if o: 

rv.append(o/x) 

return Add(*rv) 

 

def _eval_as_leading_term(self, x): 

series_gen = self.expr.lseries(x) 

d = S.Zero 

for leading_term in series_gen: 

d = diff(leading_term, *self.variables) 

if d != 0: 

break 

return d 

 

def _sage_(self): 

import sage.all as sage 

args = [arg._sage_() for arg in self.args] 

return sage.derivative(*args) 

 

 

class Lambda(Expr): 

""" 

Lambda(x, expr) represents a lambda function similar to Python's 

'lambda x: expr'. A function of several variables is written as 

Lambda((x, y, ...), expr). 

 

A simple example: 

 

>>> from sympy import Lambda 

>>> from sympy.abc import x 

>>> f = Lambda(x, x**2) 

>>> f(4) 

16 

 

For multivariate functions, use: 

 

>>> from sympy.abc import y, z, t 

>>> f2 = Lambda((x, y, z, t), x + y**z + t**z) 

>>> f2(1, 2, 3, 4) 

73 

 

A handy shortcut for lots of arguments: 

 

>>> p = x, y, z 

>>> f = Lambda(p, x + y*z) 

>>> f(*p) 

x + y*z 

 

""" 

is_Function = True 

 

def __new__(cls, variables, expr): 

from sympy.sets.sets import FiniteSet 

v = list(variables) if iterable(variables) else [variables] 

for i in v: 

if not getattr(i, 'is_Symbol', False): 

raise TypeError('variable is not a symbol: %s' % i) 

if len(v) == 1 and v[0] == expr: 

return S.IdentityFunction 

 

obj = Expr.__new__(cls, Tuple(*v), sympify(expr)) 

obj.nargs = FiniteSet(len(v)) 

return obj 

 

@property 

def variables(self): 

"""The variables used in the internal representation of the function""" 

return self._args[0] 

 

@property 

def expr(self): 

"""The return value of the function""" 

return self._args[1] 

 

@property 

def free_symbols(self): 

return self.expr.free_symbols - set(self.variables) 

 

def __call__(self, *args): 

n = len(args) 

if n not in self.nargs: # Lambda only ever has 1 value in nargs 

# XXX: exception message must be in exactly this format to 

# make it work with NumPy's functions like vectorize(). See, 

# for example, https://github.com/numpy/numpy/issues/1697. 

# The ideal solution would be just to attach metadata to 

# the exception and change NumPy to take advantage of this. 

## XXX does this apply to Lambda? If not, remove this comment. 

temp = ('%(name)s takes exactly %(args)s ' 

'argument%(plural)s (%(given)s given)') 

raise TypeError(temp % { 

'name': self, 

'args': list(self.nargs)[0], 

'plural': 's'*(list(self.nargs)[0] != 1), 

'given': n}) 

return self.expr.xreplace(dict(list(zip(self.variables, args)))) 

 

def __eq__(self, other): 

if not isinstance(other, Lambda): 

return False 

if self.nargs != other.nargs: 

return False 

 

selfexpr = self.args[1] 

otherexpr = other.args[1] 

otherexpr = otherexpr.xreplace(dict(list(zip(other.args[0], self.args[0])))) 

return selfexpr == otherexpr 

 

def __ne__(self, other): 

return not(self == other) 

 

def __hash__(self): 

return super(Lambda, self).__hash__() 

 

def _hashable_content(self): 

return (self.expr.xreplace(self.canonical_variables),) 

 

@property 

def is_identity(self): 

"""Return ``True`` if this ``Lambda`` is an identity function. """ 

if len(self.args) == 2: 

return self.args[0] == self.args[1] 

else: 

return None 

 

 

class Subs(Expr): 

""" 

Represents unevaluated substitutions of an expression. 

 

``Subs(expr, x, x0)`` receives 3 arguments: an expression, a variable or 

list of distinct variables and a point or list of evaluation points 

corresponding to those variables. 

 

``Subs`` objects are generally useful to represent unevaluated derivatives 

calculated at a point. 

 

The variables may be expressions, but they are subjected to the limitations 

of subs(), so it is usually a good practice to use only symbols for 

variables, since in that case there can be no ambiguity. 

 

There's no automatic expansion - use the method .doit() to effect all 

possible substitutions of the object and also of objects inside the 

expression. 

 

When evaluating derivatives at a point that is not a symbol, a Subs object 

is returned. One is also able to calculate derivatives of Subs objects - in 

this case the expression is always expanded (for the unevaluated form, use 

Derivative()). 

 

A simple example: 

 

>>> from sympy import Subs, Function, sin 

>>> from sympy.abc import x, y, z 

>>> f = Function('f') 

>>> e = Subs(f(x).diff(x), x, y) 

>>> e.subs(y, 0) 

Subs(Derivative(f(x), x), (x,), (0,)) 

>>> e.subs(f, sin).doit() 

cos(y) 

 

An example with several variables: 

 

>>> Subs(f(x)*sin(y) + z, (x, y), (0, 1)) 

Subs(z + f(x)*sin(y), (x, y), (0, 1)) 

>>> _.doit() 

z + f(0)*sin(1) 

 

""" 

def __new__(cls, expr, variables, point, **assumptions): 

from sympy import Symbol 

if not is_sequence(variables, Tuple): 

variables = [variables] 

variables = list(sympify(variables)) 

 

if list(uniq(variables)) != variables: 

repeated = [ v for v in set(variables) if variables.count(v) > 1 ] 

raise ValueError('cannot substitute expressions %s more than ' 

'once.' % repeated) 

 

point = Tuple(*(point if is_sequence(point, Tuple) else [point])) 

 

if len(point) != len(variables): 

raise ValueError('Number of point values must be the same as ' 

'the number of variables.') 

 

expr = sympify(expr) 

 

# use symbols with names equal to the point value (with preppended _) 

# to give a variable-independent expression 

pre = "_" 

pts = sorted(set(point), key=default_sort_key) 

from sympy.printing import StrPrinter 

class CustomStrPrinter(StrPrinter): 

def _print_Dummy(self, expr): 

return str(expr) + str(expr.dummy_index) 

def mystr(expr, **settings): 

p = CustomStrPrinter(settings) 

return p.doprint(expr) 

while 1: 

s_pts = {p: Symbol(pre + mystr(p)) for p in pts} 

reps = [(v, s_pts[p]) 

for v, p in zip(variables, point)] 

# if any underscore-preppended symbol is already a free symbol 

# and is a variable with a different point value, then there 

# is a clash, e.g. _0 clashes in Subs(_0 + _1, (_0, _1), (1, 0)) 

# because the new symbol that would be created is _1 but _1 

# is already mapped to 0 so __0 and __1 are used for the new 

# symbols 

if any(r in expr.free_symbols and 

r in variables and 

Symbol(pre + mystr(point[variables.index(r)])) != r 

for _, r in reps): 

pre += "_" 

continue 

break 

 

obj = Expr.__new__(cls, expr, Tuple(*variables), point) 

obj._expr = expr.subs(reps) 

return obj 

 

def _eval_is_commutative(self): 

return self.expr.is_commutative 

 

def doit(self): 

return self.expr.doit().subs(list(zip(self.variables, self.point))) 

 

def evalf(self, prec=None, **options): 

return self.doit().evalf(prec, **options) 

 

n = evalf 

 

@property 

def variables(self): 

"""The variables to be evaluated""" 

return self._args[1] 

 

@property 

def expr(self): 

"""The expression on which the substitution operates""" 

return self._args[0] 

 

@property 

def point(self): 

"""The values for which the variables are to be substituted""" 

return self._args[2] 

 

@property 

def free_symbols(self): 

return (self.expr.free_symbols - set(self.variables) | 

set(self.point.free_symbols)) 

 

def _has(self, pattern): 

if pattern in self.variables and pattern not in self.point: 

return False 

return super(Subs, self)._has(pattern) 

 

def __eq__(self, other): 

if not isinstance(other, Subs): 

return False 

return self._expr == other._expr 

 

def __ne__(self, other): 

return not(self == other) 

 

def __hash__(self): 

return super(Subs, self).__hash__() 

 

def _hashable_content(self): 

return (self._expr.xreplace(self.canonical_variables),) 

 

def _eval_subs(self, old, new): 

if old in self.variables: 

if old in self.point: 

newpoint = tuple(new if i == old else i for i in self.point) 

return self.func(self.expr, self.variables, newpoint) 

return self 

 

def _eval_derivative(self, s): 

if s not in self.free_symbols: 

return S.Zero 

return self.func(self.expr.diff(s), self.variables, self.point).doit() \ 

+ Add(*[ Subs(point.diff(s) * self.expr.diff(arg), 

self.variables, self.point).doit() for arg, 

point in zip(self.variables, self.point) ]) 

 

def _eval_nseries(self, x, n, logx): 

if x in self.point: 

# x is the variable being substituted into 

apos = self.point.index(x) 

other = self.variables[apos] 

arg = self.expr.nseries(other, n=n, logx=logx) 

o = arg.getO() 

subs_args = [self.func(a, *self.args[1:]) for a in arg.removeO().args] 

return Add(*subs_args) + o.subs(other, x) 

arg = self.expr.nseries(x, n=n, logx=logx) 

o = arg.getO() 

subs_args = [self.func(a, *self.args[1:]) for a in arg.removeO().args] 

return Add(*subs_args) + o 

 

def _eval_as_leading_term(self, x): 

if x in self.point: 

ipos = self.point.index(x) 

xvar = self.variables[ipos] 

return self.expr.as_leading_term(xvar) 

if x in self.variables: 

# if `x` is a dummy variable, it means it won't exist after the 

# substitution has been performed: 

return self 

# The variable is independent of the substitution: 

return self.expr.as_leading_term(x) 

 

 

def diff(f, *symbols, **kwargs): 

""" 

Differentiate f with respect to symbols. 

 

This is just a wrapper to unify .diff() and the Derivative class; its 

interface is similar to that of integrate(). You can use the same 

shortcuts for multiple variables as with Derivative. For example, 

diff(f(x), x, x, x) and diff(f(x), x, 3) both return the third derivative 

of f(x). 

 

You can pass evaluate=False to get an unevaluated Derivative class. Note 

that if there are 0 symbols (such as diff(f(x), x, 0), then the result will 

be the function (the zeroth derivative), even if evaluate=False. 

 

Examples 

======== 

 

>>> from sympy import sin, cos, Function, diff 

>>> from sympy.abc import x, y 

>>> f = Function('f') 

 

>>> diff(sin(x), x) 

cos(x) 

>>> diff(f(x), x, x, x) 

Derivative(f(x), x, x, x) 

>>> diff(f(x), x, 3) 

Derivative(f(x), x, x, x) 

>>> diff(sin(x)*cos(y), x, 2, y, 2) 

sin(x)*cos(y) 

 

>>> type(diff(sin(x), x)) 

cos 

>>> type(diff(sin(x), x, evaluate=False)) 

<class 'sympy.core.function.Derivative'> 

>>> type(diff(sin(x), x, 0)) 

sin 

>>> type(diff(sin(x), x, 0, evaluate=False)) 

sin 

 

>>> diff(sin(x)) 

cos(x) 

>>> diff(sin(x*y)) 

Traceback (most recent call last): 

... 

ValueError: specify differentiation variables to differentiate sin(x*y) 

 

Note that ``diff(sin(x))`` syntax is meant only for convenience 

in interactive sessions and should be avoided in library code. 

 

References 

========== 

 

http://reference.wolfram.com/legacy/v5_2/Built-inFunctions/AlgebraicComputation/Calculus/D.html 

 

See Also 

======== 

 

Derivative 

sympy.geometry.util.idiff: computes the derivative implicitly 

 

""" 

kwargs.setdefault('evaluate', True) 

try: 

return f._eval_diff(*symbols, **kwargs) 

except AttributeError: 

pass 

return Derivative(f, *symbols, **kwargs) 

 

 

def expand(e, deep=True, modulus=None, power_base=True, power_exp=True, 

mul=True, log=True, multinomial=True, basic=True, **hints): 

""" 

Expand an expression using methods given as hints. 

 

Hints evaluated unless explicitly set to False are: ``basic``, ``log``, 

``multinomial``, ``mul``, ``power_base``, and ``power_exp`` The following 

hints are supported but not applied unless set to True: ``complex``, 

``func``, and ``trig``. In addition, the following meta-hints are 

supported by some or all of the other hints: ``frac``, ``numer``, 

``denom``, ``modulus``, and ``force``. ``deep`` is supported by all 

hints. Additionally, subclasses of Expr may define their own hints or 

meta-hints. 

 

The ``basic`` hint is used for any special rewriting of an object that 

should be done automatically (along with the other hints like ``mul``) 

when expand is called. This is a catch-all hint to handle any sort of 

expansion that may not be described by the existing hint names. To use 

this hint an object should override the ``_eval_expand_basic`` method. 

Objects may also define their own expand methods, which are not run by 

default. See the API section below. 

 

If ``deep`` is set to ``True`` (the default), things like arguments of 

functions are recursively expanded. Use ``deep=False`` to only expand on 

the top level. 

 

If the ``force`` hint is used, assumptions about variables will be ignored 

in making the expansion. 

 

Hints 

===== 

 

These hints are run by default 

 

mul 

--- 

 

Distributes multiplication over addition: 

 

>>> from sympy import cos, exp, sin 

>>> from sympy.abc import x, y, z 

>>> (y*(x + z)).expand(mul=True) 

x*y + y*z 

 

multinomial 

----------- 

 

Expand (x + y + ...)**n where n is a positive integer. 

 

>>> ((x + y + z)**2).expand(multinomial=True) 

x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2 

 

power_exp 

--------- 

 

Expand addition in exponents into multiplied bases. 

 

>>> exp(x + y).expand(power_exp=True) 

exp(x)*exp(y) 

>>> (2**(x + y)).expand(power_exp=True) 

2**x*2**y 

 

power_base 

---------- 

 

Split powers of multiplied bases. 

 

This only happens by default if assumptions allow, or if the 

``force`` meta-hint is used: 

 

>>> ((x*y)**z).expand(power_base=True) 

(x*y)**z 

>>> ((x*y)**z).expand(power_base=True, force=True) 

x**z*y**z 

>>> ((2*y)**z).expand(power_base=True) 

2**z*y**z 

 

Note that in some cases where this expansion always holds, SymPy performs 

it automatically: 

 

>>> (x*y)**2 

x**2*y**2 

 

log 

--- 

 

Pull out power of an argument as a coefficient and split logs products 

into sums of logs. 

 

Note that these only work if the arguments of the log function have the 

proper assumptions--the arguments must be positive and the exponents must 

be real--or else the ``force`` hint must be True: 

 

>>> from sympy import log, symbols 

>>> log(x**2*y).expand(log=True) 

log(x**2*y) 

>>> log(x**2*y).expand(log=True, force=True) 

2*log(x) + log(y) 

>>> x, y = symbols('x,y', positive=True) 

>>> log(x**2*y).expand(log=True) 

2*log(x) + log(y) 

 

basic 

----- 

 

This hint is intended primarily as a way for custom subclasses to enable 

expansion by default. 

 

These hints are not run by default: 

 

complex 

------- 

 

Split an expression into real and imaginary parts. 

 

>>> x, y = symbols('x,y') 

>>> (x + y).expand(complex=True) 

re(x) + re(y) + I*im(x) + I*im(y) 

>>> cos(x).expand(complex=True) 

-I*sin(re(x))*sinh(im(x)) + cos(re(x))*cosh(im(x)) 

 

Note that this is just a wrapper around ``as_real_imag()``. Most objects 

that wish to redefine ``_eval_expand_complex()`` should consider 

redefining ``as_real_imag()`` instead. 

 

func 

---- 

 

Expand other functions. 

 

>>> from sympy import gamma 

>>> gamma(x + 1).expand(func=True) 

x*gamma(x) 

 

trig 

---- 

 

Do trigonometric expansions. 

 

>>> cos(x + y).expand(trig=True) 

-sin(x)*sin(y) + cos(x)*cos(y) 

>>> sin(2*x).expand(trig=True) 

2*sin(x)*cos(x) 

 

Note that the forms of ``sin(n*x)`` and ``cos(n*x)`` in terms of ``sin(x)`` 

and ``cos(x)`` are not unique, due to the identity `\sin^2(x) + \cos^2(x) 

= 1`. The current implementation uses the form obtained from Chebyshev 

polynomials, but this may change. See `this MathWorld article 

<http://mathworld.wolfram.com/Multiple-AngleFormulas.html>`_ for more 

information. 

 

Notes 

===== 

 

- You can shut off unwanted methods:: 

 

>>> (exp(x + y)*(x + y)).expand() 

x*exp(x)*exp(y) + y*exp(x)*exp(y) 

>>> (exp(x + y)*(x + y)).expand(power_exp=False) 

x*exp(x + y) + y*exp(x + y) 

>>> (exp(x + y)*(x + y)).expand(mul=False) 

(x + y)*exp(x)*exp(y) 

 

- Use deep=False to only expand on the top level:: 

 

>>> exp(x + exp(x + y)).expand() 

exp(x)*exp(exp(x)*exp(y)) 

>>> exp(x + exp(x + y)).expand(deep=False) 

exp(x)*exp(exp(x + y)) 

 

- Hints are applied in an arbitrary, but consistent order (in the current 

implementation, they are applied in alphabetical order, except 

multinomial comes before mul, but this may change). Because of this, 

some hints may prevent expansion by other hints if they are applied 

first. For example, ``mul`` may distribute multiplications and prevent 

``log`` and ``power_base`` from expanding them. Also, if ``mul`` is 

applied before ``multinomial`, the expression might not be fully 

distributed. The solution is to use the various ``expand_hint`` helper 

functions or to use ``hint=False`` to this function to finely control 

which hints are applied. Here are some examples:: 

 

>>> from sympy import expand, expand_mul, expand_power_base 

>>> x, y, z = symbols('x,y,z', positive=True) 

 

>>> expand(log(x*(y + z))) 

log(x) + log(y + z) 

 

Here, we see that ``log`` was applied before ``mul``. To get the mul 

expanded form, either of the following will work:: 

 

>>> expand_mul(log(x*(y + z))) 

log(x*y + x*z) 

>>> expand(log(x*(y + z)), log=False) 

log(x*y + x*z) 

 

A similar thing can happen with the ``power_base`` hint:: 

 

>>> expand((x*(y + z))**x) 

(x*y + x*z)**x 

 

To get the ``power_base`` expanded form, either of the following will 

work:: 

 

>>> expand((x*(y + z))**x, mul=False) 

x**x*(y + z)**x 

>>> expand_power_base((x*(y + z))**x) 

x**x*(y + z)**x 

 

>>> expand((x + y)*y/x) 

y + y**2/x 

 

The parts of a rational expression can be targeted:: 

 

>>> expand((x + y)*y/x/(x + 1), frac=True) 

(x*y + y**2)/(x**2 + x) 

>>> expand((x + y)*y/x/(x + 1), numer=True) 

(x*y + y**2)/(x*(x + 1)) 

>>> expand((x + y)*y/x/(x + 1), denom=True) 

y*(x + y)/(x**2 + x) 

 

- The ``modulus`` meta-hint can be used to reduce the coefficients of an 

expression post-expansion:: 

 

>>> expand((3*x + 1)**2) 

9*x**2 + 6*x + 1 

>>> expand((3*x + 1)**2, modulus=5) 

4*x**2 + x + 1 

 

- Either ``expand()`` the function or ``.expand()`` the method can be 

used. Both are equivalent:: 

 

>>> expand((x + 1)**2) 

x**2 + 2*x + 1 

>>> ((x + 1)**2).expand() 

x**2 + 2*x + 1 

 

API 

=== 

 

Objects can define their own expand hints by defining 

``_eval_expand_hint()``. The function should take the form:: 

 

def _eval_expand_hint(self, **hints): 

# Only apply the method to the top-level expression 

... 

 

See also the example below. Objects should define ``_eval_expand_hint()`` 

methods only if ``hint`` applies to that specific object. The generic 

``_eval_expand_hint()`` method defined in Expr will handle the no-op case. 

 

Each hint should be responsible for expanding that hint only. 

Furthermore, the expansion should be applied to the top-level expression 

only. ``expand()`` takes care of the recursion that happens when 

``deep=True``. 

 

You should only call ``_eval_expand_hint()`` methods directly if you are 

100% sure that the object has the method, as otherwise you are liable to 

get unexpected ``AttributeError``s. Note, again, that you do not need to 

recursively apply the hint to args of your object: this is handled 

automatically by ``expand()``. ``_eval_expand_hint()`` should 

generally not be used at all outside of an ``_eval_expand_hint()`` method. 

If you want to apply a specific expansion from within another method, use 

the public ``expand()`` function, method, or ``expand_hint()`` functions. 

 

In order for expand to work, objects must be rebuildable by their args, 

i.e., ``obj.func(*obj.args) == obj`` must hold. 

 

Expand methods are passed ``**hints`` so that expand hints may use 

'metahints'--hints that control how different expand methods are applied. 

For example, the ``force=True`` hint described above that causes 

``expand(log=True)`` to ignore assumptions is such a metahint. The 

``deep`` meta-hint is handled exclusively by ``expand()`` and is not 

passed to ``_eval_expand_hint()`` methods. 

 

Note that expansion hints should generally be methods that perform some 

kind of 'expansion'. For hints that simply rewrite an expression, use the 

.rewrite() API. 

 

Examples 

======== 

 

>>> from sympy import Expr, sympify 

>>> class MyClass(Expr): 

... def __new__(cls, *args): 

... args = sympify(args) 

... return Expr.__new__(cls, *args) 

... 

... def _eval_expand_double(self, **hints): 

... ''' 

... Doubles the args of MyClass. 

... 

... If there more than four args, doubling is not performed, 

... unless force=True is also used (False by default). 

... ''' 

... force = hints.pop('force', False) 

... if not force and len(self.args) > 4: 

... return self 

... return self.func(*(self.args + self.args)) 

... 

>>> a = MyClass(1, 2, MyClass(3, 4)) 

>>> a 

MyClass(1, 2, MyClass(3, 4)) 

>>> a.expand(double=True) 

MyClass(1, 2, MyClass(3, 4, 3, 4), 1, 2, MyClass(3, 4, 3, 4)) 

>>> a.expand(double=True, deep=False) 

MyClass(1, 2, MyClass(3, 4), 1, 2, MyClass(3, 4)) 

 

>>> b = MyClass(1, 2, 3, 4, 5) 

>>> b.expand(double=True) 

MyClass(1, 2, 3, 4, 5) 

>>> b.expand(double=True, force=True) 

MyClass(1, 2, 3, 4, 5, 1, 2, 3, 4, 5) 

 

See Also 

======== 

 

expand_log, expand_mul, expand_multinomial, expand_complex, expand_trig, 

expand_power_base, expand_power_exp, expand_func, hyperexpand 

 

""" 

# don't modify this; modify the Expr.expand method 

hints['power_base'] = power_base 

hints['power_exp'] = power_exp 

hints['mul'] = mul 

hints['log'] = log 

hints['multinomial'] = multinomial 

hints['basic'] = basic 

return sympify(e).expand(deep=deep, modulus=modulus, **hints) 

 

# This is a special application of two hints 

 

def _mexpand(expr, recursive=False): 

# expand multinomials and then expand products; this may not always 

# be sufficient to give a fully expanded expression (see 

# test_issue_8247_8354 in test_arit) 

if expr is None: 

return 

was = None 

while was != expr: 

was, expr = expr, expand_mul(expand_multinomial(expr)) 

if not recursive: 

break 

return expr 

 

 

# These are simple wrappers around single hints. 

 

 

def expand_mul(expr, deep=True): 

""" 

Wrapper around expand that only uses the mul hint. See the expand 

docstring for more information. 

 

Examples 

======== 

 

>>> from sympy import symbols, expand_mul, exp, log 

>>> x, y = symbols('x,y', positive=True) 

>>> expand_mul(exp(x+y)*(x+y)*log(x*y**2)) 

x*exp(x + y)*log(x*y**2) + y*exp(x + y)*log(x*y**2) 

 

""" 

return sympify(expr).expand(deep=deep, mul=True, power_exp=False, 

power_base=False, basic=False, multinomial=False, log=False) 

 

 

def expand_multinomial(expr, deep=True): 

""" 

Wrapper around expand that only uses the multinomial hint. See the expand 

docstring for more information. 

 

Examples 

======== 

 

>>> from sympy import symbols, expand_multinomial, exp 

>>> x, y = symbols('x y', positive=True) 

>>> expand_multinomial((x + exp(x + 1))**2) 

x**2 + 2*x*exp(x + 1) + exp(2*x + 2) 

 

""" 

return sympify(expr).expand(deep=deep, mul=False, power_exp=False, 

power_base=False, basic=False, multinomial=True, log=False) 

 

 

def expand_log(expr, deep=True, force=False): 

""" 

Wrapper around expand that only uses the log hint. See the expand 

docstring for more information. 

 

Examples 

======== 

 

>>> from sympy import symbols, expand_log, exp, log 

>>> x, y = symbols('x,y', positive=True) 

>>> expand_log(exp(x+y)*(x+y)*log(x*y**2)) 

(x + y)*(log(x) + 2*log(y))*exp(x + y) 

 

""" 

return sympify(expr).expand(deep=deep, log=True, mul=False, 

power_exp=False, power_base=False, multinomial=False, 

basic=False, force=force) 

 

 

def expand_func(expr, deep=True): 

""" 

Wrapper around expand that only uses the func hint. See the expand 

docstring for more information. 

 

Examples 

======== 

 

>>> from sympy import expand_func, gamma 

>>> from sympy.abc import x 

>>> expand_func(gamma(x + 2)) 

x*(x + 1)*gamma(x) 

 

""" 

return sympify(expr).expand(deep=deep, func=True, basic=False, 

log=False, mul=False, power_exp=False, power_base=False, multinomial=False) 

 

 

def expand_trig(expr, deep=True): 

""" 

Wrapper around expand that only uses the trig hint. See the expand 

docstring for more information. 

 

Examples 

======== 

 

>>> from sympy import expand_trig, sin 

>>> from sympy.abc import x, y 

>>> expand_trig(sin(x+y)*(x+y)) 

(x + y)*(sin(x)*cos(y) + sin(y)*cos(x)) 

 

""" 

return sympify(expr).expand(deep=deep, trig=True, basic=False, 

log=False, mul=False, power_exp=False, power_base=False, multinomial=False) 

 

 

def expand_complex(expr, deep=True): 

""" 

Wrapper around expand that only uses the complex hint. See the expand 

docstring for more information. 

 

Examples 

======== 

 

>>> from sympy import expand_complex, exp, sqrt, I 

>>> from sympy.abc import z 

>>> expand_complex(exp(z)) 

I*exp(re(z))*sin(im(z)) + exp(re(z))*cos(im(z)) 

>>> expand_complex(sqrt(I)) 

sqrt(2)/2 + sqrt(2)*I/2 

 

See Also 

======== 

Expr.as_real_imag 

""" 

return sympify(expr).expand(deep=deep, complex=True, basic=False, 

log=False, mul=False, power_exp=False, power_base=False, multinomial=False) 

 

 

def expand_power_base(expr, deep=True, force=False): 

""" 

Wrapper around expand that only uses the power_base hint. 

 

See the expand docstring for more information. 

 

A wrapper to expand(power_base=True) which separates a power with a base 

that is a Mul into a product of powers, without performing any other 

expansions, provided that assumptions about the power's base and exponent 

allow. 

 

deep=False (default is True) will only apply to the top-level expression. 

 

force=True (default is False) will cause the expansion to ignore 

assumptions about the base and exponent. When False, the expansion will 

only happen if the base is non-negative or the exponent is an integer. 

 

>>> from sympy.abc import x, y, z 

>>> from sympy import expand_power_base, sin, cos, exp 

 

>>> (x*y)**2 

x**2*y**2 

 

>>> (2*x)**y 

(2*x)**y 

>>> expand_power_base(_) 

2**y*x**y 

 

>>> expand_power_base((x*y)**z) 

(x*y)**z 

>>> expand_power_base((x*y)**z, force=True) 

x**z*y**z 

>>> expand_power_base(sin((x*y)**z), deep=False) 

sin((x*y)**z) 

>>> expand_power_base(sin((x*y)**z), force=True) 

sin(x**z*y**z) 

 

>>> expand_power_base((2*sin(x))**y + (2*cos(x))**y) 

2**y*sin(x)**y + 2**y*cos(x)**y 

 

>>> expand_power_base((2*exp(y))**x) 

2**x*exp(y)**x 

 

>>> expand_power_base((2*cos(x))**y) 

2**y*cos(x)**y 

 

Notice that sums are left untouched. If this is not the desired behavior, 

apply full ``expand()`` to the expression: 

 

>>> expand_power_base(((x+y)*z)**2) 

z**2*(x + y)**2 

>>> (((x+y)*z)**2).expand() 

x**2*z**2 + 2*x*y*z**2 + y**2*z**2 

 

>>> expand_power_base((2*y)**(1+z)) 

2**(z + 1)*y**(z + 1) 

>>> ((2*y)**(1+z)).expand() 

2*2**z*y*y**z 

 

""" 

return sympify(expr).expand(deep=deep, log=False, mul=False, 

power_exp=False, power_base=True, multinomial=False, 

basic=False, force=force) 

 

 

def expand_power_exp(expr, deep=True): 

""" 

Wrapper around expand that only uses the power_exp hint. 

 

See the expand docstring for more information. 

 

Examples 

======== 

 

>>> from sympy import expand_power_exp 

>>> from sympy.abc import x, y 

>>> expand_power_exp(x**(y + 2)) 

x**2*x**y 

""" 

return sympify(expr).expand(deep=deep, complex=False, basic=False, 

log=False, mul=False, power_exp=True, power_base=False, multinomial=False) 

 

 

def count_ops(expr, visual=False): 

""" 

Return a representation (integer or expression) of the operations in expr. 

 

If ``visual`` is ``False`` (default) then the sum of the coefficients of the 

visual expression will be returned. 

 

If ``visual`` is ``True`` then the number of each type of operation is shown 

with the core class types (or their virtual equivalent) multiplied by the 

number of times they occur. 

 

If expr is an iterable, the sum of the op counts of the 

items will be returned. 

 

Examples 

======== 

 

>>> from sympy.abc import a, b, x, y 

>>> from sympy import sin, count_ops 

 

Although there isn't a SUB object, minus signs are interpreted as 

either negations or subtractions: 

 

>>> (x - y).count_ops(visual=True) 

SUB 

>>> (-x).count_ops(visual=True) 

NEG 

 

Here, there are two Adds and a Pow: 

 

>>> (1 + a + b**2).count_ops(visual=True) 

2*ADD + POW 

 

In the following, an Add, Mul, Pow and two functions: 

 

>>> (sin(x)*x + sin(x)**2).count_ops(visual=True) 

ADD + MUL + POW + 2*SIN 

 

for a total of 5: 

 

>>> (sin(x)*x + sin(x)**2).count_ops(visual=False) 

5 

 

Note that "what you type" is not always what you get. The expression 

1/x/y is translated by sympy into 1/(x*y) so it gives a DIV and MUL rather 

than two DIVs: 

 

>>> (1/x/y).count_ops(visual=True) 

DIV + MUL 

 

The visual option can be used to demonstrate the difference in 

operations for expressions in different forms. Here, the Horner 

representation is compared with the expanded form of a polynomial: 

 

>>> eq=x*(1 + x*(2 + x*(3 + x))) 

>>> count_ops(eq.expand(), visual=True) - count_ops(eq, visual=True) 

-MUL + 3*POW 

 

The count_ops function also handles iterables: 

 

>>> count_ops([x, sin(x), None, True, x + 2], visual=False) 

2 

>>> count_ops([x, sin(x), None, True, x + 2], visual=True) 

ADD + SIN 

>>> count_ops({x: sin(x), x + 2: y + 1}, visual=True) 

2*ADD + SIN 

 

""" 

from sympy import Integral, Symbol 

from sympy.simplify.radsimp import fraction 

from sympy.logic.boolalg import BooleanFunction 

 

expr = sympify(expr) 

if isinstance(expr, Expr): 

 

ops = [] 

args = [expr] 

NEG = Symbol('NEG') 

DIV = Symbol('DIV') 

SUB = Symbol('SUB') 

ADD = Symbol('ADD') 

while args: 

a = args.pop() 

 

# XXX: This is a hack to support non-Basic args 

if isinstance(a, string_types): 

continue 

 

if a.is_Rational: 

#-1/3 = NEG + DIV 

if a is not S.One: 

if a.p < 0: 

ops.append(NEG) 

if a.q != 1: 

ops.append(DIV) 

continue 

elif a.is_Mul: 

if _coeff_isneg(a): 

ops.append(NEG) 

if a.args[0] is S.NegativeOne: 

a = a.as_two_terms()[1] 

else: 

a = -a 

n, d = fraction(a) 

if n.is_Integer: 

ops.append(DIV) 

if n < 0: 

ops.append(NEG) 

args.append(d) 

continue # won't be -Mul but could be Add 

elif d is not S.One: 

if not d.is_Integer: 

args.append(d) 

ops.append(DIV) 

args.append(n) 

continue # could be -Mul 

elif a.is_Add: 

aargs = list(a.args) 

negs = 0 

for i, ai in enumerate(aargs): 

if _coeff_isneg(ai): 

negs += 1 

args.append(-ai) 

if i > 0: 

ops.append(SUB) 

else: 

args.append(ai) 

if i > 0: 

ops.append(ADD) 

if negs == len(aargs): # -x - y = NEG + SUB 

ops.append(NEG) 

elif _coeff_isneg(aargs[0]): # -x + y = SUB, but already recorded ADD 

ops.append(SUB - ADD) 

continue 

if a.is_Pow and a.exp is S.NegativeOne: 

ops.append(DIV) 

args.append(a.base) # won't be -Mul but could be Add 

continue 

if (a.is_Mul or 

a.is_Pow or 

a.is_Function or 

isinstance(a, Derivative) or 

isinstance(a, Integral)): 

 

o = Symbol(a.func.__name__.upper()) 

# count the args 

if (a.is_Mul or isinstance(a, LatticeOp)): 

ops.append(o*(len(a.args) - 1)) 

else: 

ops.append(o) 

if not a.is_Symbol: 

args.extend(a.args) 

 

elif type(expr) is dict: 

ops = [count_ops(k, visual=visual) + 

count_ops(v, visual=visual) for k, v in expr.items()] 

elif iterable(expr): 

ops = [count_ops(i, visual=visual) for i in expr] 

elif isinstance(expr, BooleanFunction): 

ops = [] 

for arg in expr.args: 

ops.append(count_ops(arg, visual=True)) 

o = Symbol(expr.func.__name__.upper()) 

ops.append(o) 

elif not isinstance(expr, Basic): 

ops = [] 

else: # it's Basic not isinstance(expr, Expr): 

if not isinstance(expr, Basic): 

raise TypeError("Invalid type of expr") 

else: 

ops = [] 

args = [expr] 

while args: 

a = args.pop() 

 

# XXX: This is a hack to support non-Basic args 

if isinstance(a, string_types): 

continue 

 

if a.args: 

o = Symbol(a.func.__name__.upper()) 

if a.is_Boolean: 

ops.append(o*(len(a.args)-1)) 

else: 

ops.append(o) 

args.extend(a.args) 

 

if not ops: 

if visual: 

return S.Zero 

return 0 

 

ops = Add(*ops) 

 

if visual: 

return ops 

 

if ops.is_Number: 

return int(ops) 

 

return sum(int((a.args or [1])[0]) for a in Add.make_args(ops)) 

 

 

def nfloat(expr, n=15, exponent=False): 

"""Make all Rationals in expr Floats except those in exponents 

(unless the exponents flag is set to True). 

 

Examples 

======== 

 

>>> from sympy.core.function import nfloat 

>>> from sympy.abc import x, y 

>>> from sympy import cos, pi, sqrt 

>>> nfloat(x**4 + x/2 + cos(pi/3) + 1 + sqrt(y)) 

x**4 + 0.5*x + sqrt(y) + 1.5 

>>> nfloat(x**4 + sqrt(y), exponent=True) 

x**4.0 + y**0.5 

 

""" 

from sympy.core.power import Pow 

from sympy.polys.rootoftools import RootOf 

 

if iterable(expr, exclude=string_types): 

if isinstance(expr, (dict, Dict)): 

return type(expr)([(k, nfloat(v, n, exponent)) for k, v in 

list(expr.items())]) 

return type(expr)([nfloat(a, n, exponent) for a in expr]) 

rv = sympify(expr) 

 

if rv.is_Number: 

return Float(rv, n) 

elif rv.is_number: 

# evalf doesn't always set the precision 

rv = rv.n(n) 

if rv.is_Number: 

rv = Float(rv.n(n), n) 

else: 

pass # pure_complex(rv) is likely True 

return rv 

 

# watch out for RootOf instances that don't like to have 

# their exponents replaced with Dummies and also sometimes have 

# problems with evaluating at low precision (issue 6393) 

rv = rv.xreplace({ro: ro.n(n) for ro in rv.atoms(RootOf)}) 

 

if not exponent: 

reps = [(p, Pow(p.base, Dummy())) for p in rv.atoms(Pow)] 

rv = rv.xreplace(dict(reps)) 

rv = rv.n(n) 

if not exponent: 

rv = rv.xreplace({d.exp: p.exp for p, d in reps}) 

else: 

# Pow._eval_evalf special cases Integer exponents so if 

# exponent is suppose to be handled we have to do so here 

rv = rv.xreplace(Transform( 

lambda x: Pow(x.base, Float(x.exp, n)), 

lambda x: x.is_Pow and x.exp.is_Integer)) 

 

return rv.xreplace(Transform( 

lambda x: x.func(*nfloat(x.args, n, exponent)), 

lambda x: isinstance(x, Function))) 

 

 

from sympy.core.symbol import Dummy