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

31

3

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:


You must put your corresponding outputs in your answer (n = 1 and n = 2).

Winning

The shortest code in bytes wins.

Beta Decay

Posted 2017-04-13T08:35:42.610

Reputation: 21 478

37ASCII art is disallowed. (ಥ﹏ಥ) – Albert Renshaw – 2017-04-13T08:40:39.370

1Can the axes be on the left and bottom edges of the graph? instead of at the centre? – user41805 – 2017-04-13T08:41:52.780

"The axes do not have numbers" but the examples have numbers on the axes – user41805 – 2017-04-13T08:43:51.410

@Kritixi As long as the domain of the graph is from -3 to 3, yes – Beta Decay – 2017-04-13T08:44:22.137

@Kritixi You'll just have to ignore those since I couldn't find a graphing service without numbers – Beta Decay – 2017-04-13T08:45:28.273

2"If an image is output, it each side must be longer than 500 pixels." Are vector graphics allowed? – Martin Ender – 2017-04-13T08:46:00.597

1@MartinEnder Yes, I suppose so – Beta Decay – 2017-04-13T08:47:20.963

1Should "The axes do not have numbers" read "The axes do not have to have numbers"? – Jonathan Allan – 2017-04-13T08:55:17.643

@JonathanAllen Yes, sorry, it was a typo – Beta Decay – 2017-04-13T09:01:23.150

@BetaDecay Can I suggest making the axes optional to give languages that do not have builtin plot functions a chance? – user41805 – 2017-04-13T09:06:09.807

@Kritixi Axes are now optional – Beta Decay – 2017-04-13T09:18:23.747

4Why am I not surprised to see MATLAB, MATL and Mathematica as some of the first answers. :) – Kevin Cruijssen – 2017-04-13T11:12:17.223

Where is C++? :'( – Failed Scientist – 2017-04-14T09:34:44.073

Your examples are smaller than 500 pixels in both directions. – Ruslan – 2017-04-14T12:21:04.213

"The output may be in any format you wish" and "ASCII art is disallowed" contradict each other. – user253751 – 2017-04-15T11:30:33.280

@immibis Not really, when the question tag is [tag:graphical-output] – Beta Decay – 2017-04-15T11:38:45.403

+1 for banning ascii art >:] – 12Me21 – 2018-07-16T04:02:07.963

Answers

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

flawr

Posted 2017-04-13T08:35:42.610

Reputation: 40 560

21

TI-Basic, 26 21 bytes

~3→Xmin
3→Xmax
Prompt N
DrawF N^Xcos(πX

Output for N=2:

TI84SE GRAPH OUTPUT

Timtech

Posted 2017-04-13T08:35:42.610

Reputation: 12 038

Code screenshot: https://i.stack.imgur.com/jct97.png

– Timtech – 2017-04-13T14:08:17.980

1I count 47 characters in your code, not 26. – Konrad Rudolph – 2017-04-13T14:29:42.693

11

@KonradRudolph See: TI-Basic scoring guidelines.

– Addison Crump – 2017-04-13T14:44:48.757

5"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 – 2017-04-13T17:20:13.130

7@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 – 2017-04-14T02:37:53.893

1Who would've thought that a graphing calculator could graph things! – PyRulez – 2017-04-15T19:09:34.933

1

You can save 4 bytes with DrawF, eg. DrawF N^Xcos(πX

– pizzapants184 – 2017-04-21T15:34:04.197

1@pizzapants184 You're absolutely right, I should have thought of that! Thanks. – Timtech – 2017-04-21T18:18:33.860

15

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:

R. Kap

Posted 2017-04-13T08:35:42.610

Reputation: 4 730

1+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 – 2017-04-14T13:52:14.380

5You can save 11 bytes by using abbreviations: gnuplot -e "se t png;p[-3:3]real((-2)**x)">A – Noiralef – 2017-04-14T14:21:41.403

@Noiralef Thanks! :) – R. Kap – 2017-04-15T17:06:03.640

13

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

n=2 n=1

Jonathan Allan

Posted 2017-04-13T08:35:42.610

Reputation: 67 804

2Can you get rid of from matplotlib.pyplot import* if you start ipython with the --pylab --matplotlib flag? – Ajasja – 2017-04-14T11:56:00.103

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 – 2017-04-14T12:10:26.317

yup, works with --pylab (tested with python 2) – Ajasja – 2017-04-14T12:28:40.863

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 – 2017-04-14T12:40:25.193

1Yes, 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 – 2017-04-14T12:57:23.657

Wouldn't from pylab import* also give you plot and show? – DSM – 2017-04-15T20:21:58.647

@DSM, so it would, I had no idea about the existence of that as a separate module - thanks. – Jonathan Allan – 2017-04-15T20:26:28.553

That's probably a good sign, it's too stateful an interface and so it's out of favour these days. :-) – DSM – 2017-04-15T20:27:04.510

Oh wow, yes that is flat; len(dir(pylab))=961 here! – Jonathan Allan – 2017-04-15T20:30:47.683

I'm not completely sure if there is a difference between this and Ajasja's answer anymore... – Beta Decay – 2017-04-17T10:09:37.353

@BetaDecay yes they have certainly merged - the presence of the pylab module here did most of that really. I don't think there is reason to delete though. – Jonathan Allan – 2017-04-17T12:34:59.700

11

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.

flawr

Posted 2017-04-13T08:35:42.610

Reputation: 40 560

11

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).

Martin Ender

Posted 2017-04-13T08:35:42.610

Reputation: 184 808

10

R, 30 bytes

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

n = 1

enter image description here

n = 2

enter image description here

Konrad Rudolph

Posted 2017-04-13T08:35:42.610

Reputation: 1 067

3Oooh pretty circles – Beta Decay – 2017-04-13T13:58:03.500

2@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 – 2017-04-13T14:04:52.133

5I don't think it's ugly. It looks really cool. – mbomb007 – 2017-04-13T14:25:23.120

1The x axis is labelled incorrectly. I think you need x=seq(-3,3,.05);plot(x,Re((0i-n)^x)) – user2390246 – 2017-04-13T14:51:11.263

2@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 – 2017-04-13T15:08:09.400

1OK fair point (though both MATLAB answers look fine to me...) – user2390246 – 2017-04-13T15:39:19.377

10

R, 29 bytes

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

n is provided through stdin. Result for n=1: enter image description here

And for n=2:

enter image description here

plannapus

Posted 2017-04-13T08:35:42.610

Reputation: 8 610

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 – 2017-04-15T13:37:06.260

@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 – 2017-04-15T14:07:04.187

Sorry correction: the matlab answers define functions as well. – plannapus – 2017-04-15T14:15:42.430

Well. This is a code golf … – Konrad Rudolph – 2017-04-15T15:00:56.937

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 – 2017-04-17T08:23:30.450

Fair enough but these are merely the default rules. This question seems to explicitly permit it. At any rate most of the other answers just use a variable and make the comparison this harder. My point is, this is, hands down, the shortest solution in a non golf language (minus the weird TI Basic counting rules which are essentially cheating). – Konrad Rudolph – 2017-04-17T08:32:30.377

Yes you're right and this is why i didn't downvote your answer despite it using that form of input, but allow me to respect the rules i believe in. In addition, as explained in my previous comment, i think your assumption that "most of the other answers just use a variable" is wrong: apart from yours (and maybe the postscript) I don't see any. The others use anonymous functions or, like me, a prompt. – plannapus – 2017-04-17T08:37:47.860

8

Excel VBA, 168 160 147 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
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
With ActiveSheet.Shapes.AddChart(xlLine).Chart
.SetSourceData Range("A1:A121")
.Axes(xlCategory).Delete
End With
End Sub

n=1
n=1
n=2
n=2

Engineer Toast

Posted 2017-04-13T08:35:42.610

Reputation: 5 769

1Is it not shorter to use (-n)^x instead of hardcoding pi? – Beta Decay – 2017-04-13T20:26:39.040

1@BetaDecay It would be if Excel could handle negative numbers raised to negative non-integers ¯\(ツ) – Engineer Toast – 2017-04-13T20:28:59.763

2Isn't it shorter to use atn(1)*4 for pi? – Kyle Kanos – 2017-04-15T14:04:17.467

2@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 – 2017-04-18T00:01:31.430

in your chart version, you can drop the cells(r+1,...) call below the r=r+1 call and change it to cells(r,...) for -2; also in your current version, do you think that it would be within the scope of the rules to just add an X into the relevant cell rather than coloring it black? – Taylor Scott – 2017-06-18T21:58:21.740

You can get this down to 138 bytes w/ 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 – Taylor Scott – 2018-07-16T12:38:11.380

1@TaylorScott That's three new tricks, thanks. That's more valuable than the 7 bytes they saved me this time. – Engineer Toast – 2018-07-16T12:52:09.330

@EngineerToast there are always new tricks to learn about in VBA - like the [{1,2,3}] array declaration notation for Excel VBA :) – Taylor Scott – 2018-07-16T13:02:13.297

Also you can leave the string unterminated - it will autofomat to a closed string, and there is no need to check if i=1, as 1 is a truthy value and 0 is falsy – Taylor Scott – 2018-07-16T13:06:34.133

6

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:

enter image description here

Luis Mendo

Posted 2017-04-13T08:35:42.610

Reputation: 87 464

1ezplot = la-z-plot :D (I keep forgetting about this one...) – flawr – 2017-04-13T12:53:53.353

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 – 2017-04-14T10:29:34.370

@sanchises I didn't know either :-) It was flawr's idea – Luis Mendo – 2017-04-14T13:16:40.873

5

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.

n=1 n=2

Ajasja

Posted 2017-04-13T08:35:42.610

Reputation: 340

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 – 2017-04-15T20:26:20.103

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 – 2017-04-15T21:04:14.907

@DSM Ops, fixed. – Ajasja – 2017-04-15T21:57:50.173

@JonathanAllan Thanks. – Ajasja – 2017-04-15T21:58:03.957

Ah I saved you 2 in total, you just saved me 1 by changing to arange(121)! – Jonathan Allan – 2017-04-15T22:01:06.283

I'm not completely sure if there is a difference between this and Jonathan Allen's answer anymore... – Beta Decay – 2017-04-17T10:09:53.440

@BetaDecay Well, his was first but this one is still shorter. The only remaining difference left is in the use of magic ipython commands... – Ajasja – 2017-04-18T05:30:18.687

3

Encapsulated PostScript; 232 bytes

%!PS-Adobe-3.0 EPSF-3.0
%%BoundingBox: 0 0 500 500
%%EndComments
/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...

enter image description here

enter image description here

joojaa

Posted 2017-04-13T08:35:42.610

Reputation: 363

Ooh that is nice – Beta Decay – 2017-04-16T20:50:04.923

3

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:

n = 1 n = 2

Julian Wolf

Posted 2017-04-13T08:35:42.610

Reputation: 1 139

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).

Output

Output

ATaco

Posted 2017-04-13T08:35:42.610

Reputation: 7 898

2

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 window

-(]plot@;9 o.^)i:@3j120[load@'plot'
                        load@'plot'       NB. load plotting library
               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

Adám

Posted 2017-04-13T08:35:42.610

Reputation: 37 779

I think 20%~i:@60 can be i:@3j120. – FrownyFrog – 2018-07-18T09:07:25.457

@FrownyFrog Correct. Thanks. – Adám – 2018-07-18T10:19:44.733

1

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\$: n=1

For \$n=2\$: n=2

J. Sallé

Posted 2017-04-13T08:35:42.610

Reputation: 3 233

0

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

12Me21

Posted 2017-04-13T08:35:42.610

Reputation: 6 110

0

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
    Set c = Sheet1.Shapes.AddChart(4).Chart ''  Add line plot to Sheet1 (xlLine)
    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\$

Output plot n=1

Where input, \$n=3\$

Output plot n=3

Taylor Scott

Posted 2017-04-13T08:35:42.610

Reputation: 6 709

0

Julia 0.6 with Plots.jl, 46 bytes

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

GR plot

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):

Plotly plot

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:

UnicodePlots plot

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))

sundar - Reinstate Monica

Posted 2017-04-13T08:35:42.610

Reputation: 5 296

Dang, that's some clever (ab)use of the Braille characters. – Zacharý – 2018-07-17T01:06:29.020