Draw a graph of $y=(-n)^x$

Challenge

Given an input of an integer, $n$ (where $0<n<50$), output the graph of $y=\mathrm{Re}((-n)^x)$ from $x = -3$ to $x = 3$ inclusive.

Where $\mathrm{Re}(p)$ is the real part of the complex number $p$.

Note that $\mathrm{Re}((-n)^x) = n^x \cos{(\pi x)}$

Output

The output may be in any form you wish (e.g. an image or a window etc.). ASCII art is disallowed.

The graph does not need to have axes (to allow languages without built-in graphing functions to compete).

If an image is output, it each side must be longer than 500 pixels. Similarly, the plot must fill the image as best it can.

The minimum interval between plots is 0.05.

Vector graphics are allowed.

Examples

For an input of 2:

For an input of 1:

Winning

The shortest code in bytes wins.

• ASCII art is disallowed. (ಥ﹏ಥ) – Albert Renshaw Apr 13 '17 at 8:40
• Can the axes be on the left and bottom edges of the graph? instead of at the centre? – user41805 Apr 13 '17 at 8:41
• "If an image is output, it each side must be longer than 500 pixels." Are vector graphics allowed? – Martin Ender Apr 13 '17 at 8:46
• @MartinEnder Yes, I suppose so – Beta Decay Apr 13 '17 at 8:47
• Why am I not surprised to see MATLAB, MATL and Mathematica as some of the first answers. :) – Kevin Cruijssen Apr 13 '17 at 11:12

MATL, 22 18 16 bytes

Thanks @LuisMendo for additional -2 bytes!

I_.01I3$:i_y^&XG I_ push 3 and negate .01 push 0.01 I push 3 3$:                generate the list [-3,-2.99,-2.98,...,3]
i_y^            calculate (-input)^(list)
$XG plot the first list against th real part of the second list  Try it on matl.suever.net TI-Basic, 26 21 bytes ~3→Xmin 3→Xmax Prompt N DrawF N^Xcos(πX  Output for N=2: • I count 47 characters in your code, not 26. – Konrad Rudolph Apr 13 '17 at 14:29 • @KonradRudolph See: TI-Basic scoring guidelines. – Addison Crump Apr 13 '17 at 14:44 • "If an image is output, it each side must be longer than 500 pixels." Doesn't seem like the built in graphing capability will work here. – user5090812 Apr 13 '17 at 17:20 • @user5090812 "The output may be in any form you wish (e.g. an image or a window etc.)" - I'm outputting by the graph window, not an image, so this restriction doesn't apply. – Timtech Apr 14 '17 at 2:37 • Who would've thought that a graphing calculator could graph things! – PyRulez Apr 15 '17 at 19:09 Bash + Gnuplot, 56 45 bytes (-11 bytes thanks to Noiralef!) gnuplot -e "se t png;p[-3:3]real((-$1)**x)">A


Saves the resulting graph as a png image named A in the current working directory.

Example Outputs

For n = 1:

For n = 2:

• +1 for using a langage I use everyday. (no "garbled binary nonsense" as with golf-langages ^^). This can be re-used in everyday situations. – Olivier Dulac Apr 14 '17 at 13:52
• You can save 11 bytes by using abbreviations: gnuplot -e "se t png;p[-3:3]real((-2)**x)">A – Noiralef Apr 14 '17 at 14:21
• @Noiralef Thanks! :) – R. Kap Apr 15 '17 at 17:06

Python 3 with matplotlib, 103 72 bytes

-12 bytes thanks to DSM (a module is installed alongside matplotlib called pylab with the necessary functionality "making Python in a repl more like Matlab" - odd, but true!)
-18 more as a result (pylab has many numpy functions too!)
-1 byte thanks to Ajasja (replacing arange(-60,61)/20+0j with arange(121)/20-3+0j)

from pylab import*
def f(n):x=arange(121)/20-3+0j;plot(x,(-n)**x);show()


n=2,1

• Can you get rid of from matplotlib.pyplot import* if you start ipython with the --pylab --matplotlib flag? – Ajasja Apr 14 '17 at 11:56
• Have you got iPython; does it work? I suspect it would be acceptable if it does, but would need to ask myself. I don't have iPython and have never had the need to use it. – Jonathan Allan Apr 14 '17 at 12:10
• yup, works with --pylab (tested with python 2) – Ajasja Apr 14 '17 at 12:28
• There is nothing non-standard in any config file making the display work, right? If not I'd say post it as a separate answer on this occasion since it's a clever use of a change of language IMO. EDIT: I see you have golfed it there too :) – Jonathan Allan Apr 14 '17 at 12:40
• Yes, I remembered %pylab gives you numpy as well and if you're in a notebook you don't need a show at the end:) – Ajasja Apr 14 '17 at 12:57

Mathematica, 41 bytes

Plot[Re[(-#)^x],{x,-3,3},PlotRange->All]&


Output looks exactly as shown in the challenge except for the font of the numbers (which I suspect was created with Wolfram Alpha).

MATLAB, 35 30 bytes

x=-3:.01:3;@(n)plot(x,(-n).^x)


This defines an anyonmous function. The output is via a new window with a resizable vector graphic output. MATLAB's plot automatically ignores the imaginary part of the y-coordinates as long as your provide corresponding x-coordinates.The following output is for n=3.

R, 30 bytes

plot(Re((0i-n)^seq(-3,3,.05)))


n = 2

• Oooh pretty circles – Beta Decay Apr 13 '17 at 13:58
• @BetaDecay R’s default rendering is ugly. The rationale for the default is that unfilled circles don’t hide overplotted points as much as filled circles/dots would. – Konrad Rudolph Apr 13 '17 at 14:04
• I don't think it's ugly. It looks really cool. – mbomb007 Apr 13 '17 at 14:25
• The x axis is labelled incorrectly. I think you need x=seq(-3,3,.05);plot(x,Re((0i-n)^x)) – user2390246 Apr 13 '17 at 14:51
• @user2390246 Given that the axes are completely optional, I don’t think it matters. If the axis labelling matters, other answers also have issues due to scaling (e.g. the 30-char MATLAB answer). – Konrad Rudolph Apr 13 '17 at 15:08

R, 29 bytes

curve(Re((0i-scan())^x),-3,3)


n is provided through stdin. Result for n=1:

And for n=2:

• Why not use a variable n like the other answers and shave off five characters from your answer? Anyway, crazy answer. I always forget about curve. – Konrad Rudolph Apr 15 '17 at 13:37
• @KonradRudolph Thanks. Actually most other answers don't predefine n. The matlab, matl, TI-Basic and mathematica answers take input as stdin (as far as I understand them), while the python and VBA answers create a function. Even if it's allowed, it's just a matter of personal taste: I just don't like predefining variables as a way of input. – plannapus Apr 15 '17 at 14:07
• Sorry correction: the matlab answers define functions as well. – plannapus Apr 15 '17 at 14:15
• Well. This is a code golf … – Konrad Rudolph Apr 15 '17 at 15:00
• I didn't want to be pedantic or anything but actually as a community we consider that using a predefined variable is not considered a valid input method unless stated explicitely otherwise in the question. – plannapus Apr 17 '17 at 8:23

Excel VBA, 168160147 138 Bytes (cells as pixels at 100x scale)

Saved 8 bytes thanks to KyleKanos
Saved 22 bytes thanks to Taylor Scott

Sub g(n)
For i=0To 1
For x=-3To 3Step.01
y=n^x*Cos([Pi()]*x)
m=IIf(y<m,y,m)
If i Then Cells(500*(1-y/m)+1,(x+3)*100+1)="#
Next x,i
End Sub


Formatted, it looks like this:

Sub g(n)
For i = 0 To 1
For x = -3 To 3 Step 0.01
y = n ^ x * Cos([Pi()] * x)
m = IIf(y < m, y, m)
If i Then Cells(500 * (1 - y / m) + 1, (x + 3) * 100 + 1) = "#"
Next x, i
End Sub


Fun Fact: VBA does not have a built-in pi variable so we have to evaluate it as a worksheet function where it does exist.

n=1                                                                         n=2

I started with a chart version at 193 bytes but it did get prettier results.

Sub c(n)
For x=-3To 3Step 0.05
r=r+1
Cells(r,1)=n^x*Cos(Atn(1)*4*x)
Next
.SetSourceData Range("A1:A121")
.Axes(xlCategory).Delete
End With
End Sub


n=1

n=2

• Is it not shorter to use (-n)^x instead of hardcoding pi? – Beta Decay Apr 13 '17 at 20:26
• @BetaDecay It would be if Excel could handle negative numbers raised to negative non-integers ¯\_(ツ)_/¯ – Engineer Toast Apr 13 '17 at 20:28
• Isn't it shorter to use atn(1)*4 for pi? – Kyle Kanos Apr 15 '17 at 14:04
• @KyleKanos Indeed it is, thanks. I didn't find that identity in my constants lookup table and, as an engineer, that's where I'm legally obligated to stop. – Engineer Toast Apr 18 '17 at 0:01
• @TaylorScott That's three new tricks, thanks. That's more valuable than the 7 bytes they saved me this time. – Engineer Toast Jul 16 '18 at 12:52

MATLAB, 35 33 bytes

Thanks fo @flawr for removing 2 bytes!

@(n)ezplot(@(x)real((-n)^x),-3:3)


This defines an anonymous function. To call it with input 2, use ans(2) (or assign the function to a variable such as f and then use f(2)).

Output is vector graphics (resizable window). The sampling interval on the x axis is determined automatically by the ezplot function, but it seems to be more than enough.

A warning is produced in STDERR because the function passed to ezplot (@(x)real((-n)^x)) is not vectorized, but the graph is generated.

Example for n = 2:

• ezplot = la-z-plot :D (I keep forgetting about this one...) – flawr Apr 13 '17 at 12:53
• Huh. Never knew that you could pass the domain to ezplot like that. Sadly, the same cannot be said for fplot, so no byte can be saved there. – Sanchises Apr 14 '17 at 10:29
• @sanchises I didn't know either :-) It was flawr's idea – Luis Mendo Apr 14 '17 at 13:16

Jupyter notebook and Python 3; 53 bytes

%pylab
def f(n):x=arange(121)/20-3+0j;plot(x,(-n)**x)


Three bytes saved thanks to @Jonathan Allan.

• Two minor bits: if I read the specs right, you need a minimum of 0.05 (not 0.1) between (effective) points, and we're supposed to be inclusive of 3. – DSM Apr 15 '17 at 20:26
• You can use x=arange(-60,61)/20 to fix the issues highlighted by DSM at a cost of 2 bytes. If you add 0j to the arange it can be used to change over to plot(x,(-n)**x) saving 4. – Jonathan Allan Apr 15 '17 at 21:04
• @DSM Ops, fixed. – Ajasja Apr 15 '17 at 21:57
• @JonathanAllan Thanks. – Ajasja Apr 15 '17 at 21:58
• Ah I saved you 2 in total, you just saved me 1 by changing to arange(121)! – Jonathan Allan Apr 15 '17 at 22:01

Encapsulated PostScript; 232 bytes

%!PS-Adobe-3.0 EPSF-3.0
%%BoundingBox: 0 0 500 500
/n 1 def .02 setlinewidth /f{dup dup n exch exp exch 180 mul cos mul 3 div}def
250 250 translate 80 80 scale newpath -3 f moveto -3 .05 3{f lineto}for stroke
%%EOF


Now since this is a vector image itself...

• Ooh that is nice – Beta Decay Apr 16 '17 at 20:50

TikZ + PGFPlots, 175 bytes

\documentclass{standalone}\usepackage{tikz,pgfplots}\begin{document}\typein[\n]{}\tikz{\begin{axis}\addplot[domain=-3:3,samples=120]{\n^x*cos(180*x)};\end{axis}}\end{document}


Compile with, e.g., latexmk -cd -f -pdf in.tex for a pdf output. During compilation, the user is prompted for n.

Sample outputs (converted to png) for n = 1 and n = 2:

Math.JS Grapher, 20 Bytes

r(n)=f(x)=re((-n)^x)


By sheer fluke, this graphing utility is TC (For the most part, Infinite loops just crash it.), and by nature, it's primary output is graphs.

How it works

r(n)= assigns a function r which takes the argument n to the expression f(x)=re((-n)^x). re((-n)^x) is pretty much letter for letter the challenge description. But this assigns the function f(x) to this, which the grapher implicitly outputs as a line graph.

How to test it

You can use this site, punch that function in there, then call it with r(input).

J, 37 36 bytes

Thanks to my colleague Marshall for guidance. -2 thanks to FrownyFrog.

Anonymous tacit prefix function.

-(]plot@;9 o.^)i:@3j120[load@'plot'


-(]plot@;9 o.^)i:@3j120[load@'plot'
i:@3j120                   NB. -3...3 in 120 steps
-                                         NB. negate argument
(           ^)                           NB. raise the negated value to those exponents
(       9 o. )                           NB. real part
(]     ;     )                           NB. pair with the exponents
( plot@      )                           NB. plot it

• I think 20%~i:@60 can be i:@3j120. – FrownyFrog Jul 18 '18 at 9:07
• @FrownyFrog Correct. Thanks. – Adám Jul 18 '18 at 10:19

Dyalog APL, 41 bytes

⎕SE.UCMD∊'chart x(9○(-'⍞')*x←3-20÷⍨⍳121)'


How it works:

⎕SE.UCMD∊'chart x(9○(-'⍞')*x←3-20÷⍨⍳121)' ⍝ Main function
⎕SE.UCMD∊                                 ⍝ User Command (called from the session object)
'chart                           ⍝ Plot a chart with arguments:
(           3-20÷⍨⍳121)' ⍝ Yields the list [-3, -2.95, -2.9,..., 2.9, 2.95, 3]
x←             ⍝ Assign that list to x
*               ⍝ and use it as exponent
(-'⍞')                ⍝ with (-input) as base
9○                      ⍝ discard the complex part; this generates Re((-n)^x)
x                         ⍝ And x.


The user command ]chart, in this case, takes two vector arguments, x and y and plots the graphs:

For $n=1$:

For $n=2$:

SmileBASIC, 82 bytes

INPUT N
FOR I=0TO 399X=I/66.5-3GPSET I,120-POW(N,X-3*SGN(N-1))*COS(PI()*X)*120NEXT


Graph fills the entire screen, even when N is less than 1.

When N is greater than 1, you can scale Y to be between -1 and 1 by dividing it by n^3. I'm already doing n^x, and n^x / n^3 can be simplified to n^(x-3). However, when N is less than 1, I have to divide Y by n^-3 instead. This is equivalent to n^(x+3).

I can use n^(x-3*sign(n-1)) to use -3 if n>1, and +3 if n<1

Images coming soon

Excel VBA, 133 bytes

Immediate window script that takes input from [A1] and outputs a Chart object to the Sheet1 object.

[B:B]="=ROW()/20-3.05":[C:C]="=A$1^B1*Cos(Pi()*B1)":Set c=Sheet1.Shapes.AddChart(4).Chart:c.SetSourceData[C1:C121]:c.Axes(1).Delete  Ungolfed Full Subroutine version. I/O is unchanged. Sub b() [B:B] = "=ROW()/20-3.05" '' Define x-axis [C1:C121] = "=A$1^B1*Cos(Pi()*B1)"      ''  Define y-axis in terms of input from A1
c.SetSourceData [C1:C121]               ''  Set y source to match x in [-3,3]
c.Axes(1).Delete                        ''  Remove erroneous axes (xlCategory)
End Sub


Output

Where input, $n=1$

Where input, $n=3$

Julia 0.6 with Plots.jl, 46 bytes

using Plots
~n=plot(real((0im-n).^(-3:.05:3)))


This needed a Julia representation!

Not much to golf here though, except (ab)using operator overloading to save bytes on function defintion, and using 0im-n to make the input number complex where I might usually have used Complex(n). That's necessary because in Julia, for type stability reasons, the ^ operator returns Complex results only when the input is Complex itself. So here we make it a complex number by adding 0im ie. 0i.

One cool thing about the Plots.jl package is that it automatically chooses the backend to use based on what plotting packages you have installed and where you're running the plot command from. The above plot was created with the GR backend, but if I didn't have that installed (or if I explicitly ran a plotly() command like I did for this), it would have used the more interactive Plotly backend and output this (which looks a tiny bit nicer IMO):

There's even a UnicodePlots backend, to print a plot in the terminal (or save to a text file) using Unicode characters and color codes. SE keeps messing up the plot alignment if I try to directly paste it though, so here's a terminal screenshot:

PS: The alternate formula, $Re((−n)^x)=n^xcos(πx)$, comes out to the same length:

using Plots
~n=plot(n.^(x=-3:.05:3).*cospi(x))

• Dang, that's some clever (ab)use of the Braille characters. – Zacharý Jul 17 '18 at 1:06