Calcola il valore di


16

Sfida

Dato un numero intero, , come input dove s 1 emette il valore di ζ ( s ) (Where ζ ( x )ss1ζ(s)ζ(x) rappresenta la funzione Ziem di Riemann ).

Ulteriori informazioni

ζ(s) è definito come:

ζ(s)=n=11ns

Dovresti generare la tua risposta con 5 cifre decimali (niente di più, niente di meno). Se la risposta risulta infinita, dovresti emettere o equivalente nella tua lingua.

Gli incorporamenti di Riemann Zeta sono consentiti, ma è meno divertente farlo in questo modo;)

Esempi

Le uscite devono essere esattamente come mostrato di seguito

Input -> Output
1 -> ∞ or inf etc.
2 -> 1.64493
3 -> 1.20206
4 -> 1.08232
8 -> 1.00408
19 -> 1.00000

generosità

Come consolazione per consentire i built-in, offrirò una generosità di 100 rep alla risposta più breve che non lo fa utilizza le funzioni zeta integrate. (Il segno di spunta verde continuerà comunque con la soluzione più breve in assoluto)

vincente

Vince il codice più breve in byte.


7
Questa sfida aveva un tale potenziale ... Fino a quando non hai permesso ai builtin ...
HyperNeutrino,

@HyperNeutrino Sì, l'ho pubblicato perché ho visto che la sfida consentiva i builtin. FGITW
NoOneIsHere

2
"A una precisione di 5 decimali" è rigoroso? (vale a dire che possiamo produrre con maggiore precisione?) Altrimenti i casi di test dovrebbero mostrare davvero 6dp.
Jonathan Allan,

@JonathanAllen Ho chiarito le specifiche di arrotondamento
Decadimento beta

3
@BetaDecay (Sigh No ping) deve un ingresso 19 davvero uscita del testo 1.00000? Non sarebbe 1o 1.0essere valido? Sembra che tu l'abbia trasformata in una sfida camaleontica.
Jonathan Allan,

Risposte:


11

Mathematica, 9 7 11 byte

Zeta@#~N~6&

Spiegazione:

Zeta@#       (* Zeta performed on input *)
      ~N     (* Piped into the N function *)
        ~6   (* With 6 digits (5 decimals) *)
          &  (* Make into function *)

Mathematica result

Senza incorporato:

Mathematica, 23 byte UTF-8

Sum[1/n^#,{n,∞}]~N~6&

Grazie a Kelly Lowder


3
N@*Zetasalva due byte.
Martin Ender,

@*è l'operatore di composizione (a sinistra): f@*gindica una funzione il cui valore nell'argomento xè f[g[x]].
Greg Martin,

@BetaDecay Perché 1viene emesso ComplexInfinitye arrotondato ai 5luoghi. (es. 1.64493)
NoOneIsHere

@MartinEnder Come *funziona?
NoOneIsHere

1
@NoOneIsHere usa la tua risposta N~5ma usa la tua spiegazione 6.
numbermaniac,

8

Javascript, 81 70 66 65 byte

s=>s-1?new Int8Array(1e6).reduce((a,b,i)=>a+i**-s).toFixed(5):1/0

Esempi eseguibili:

ζ=s=>s-1?new Int8Array(1e6).reduce((a,b,i)=>a+i**-s).toFixed(5):1/0

const values = [ 1, 2, 3, 4, 8, 19 ];
document.write('<pre>');
for(let s of values) {
  document.write('ζ(' + s + ') = ' + ζ(s) + '\n')
}


Perché chiamarlo Z? Il simbolo zeta è un nome di funzione valido in JS e non è necessario che sia giocato a golf.
Fondi Monica's Lawsuit

Replace Array(1e6).fill() with [...Array(1e6)], and replace the first (s) with s
Conor O'Brien

1
@QPaysTaxes Good point! Unicode variable names ftw!
Frxstrem

@ConorO'Brien Huh, I never realized that Array trick (I thought sparse arrays didn't iterate but I guess I was wrong). Thanks!
Frxstrem

@Frxstrem Note that ζ takes two bytes
CocoaBean

6

APL (Dyalog), 22 21 bytes

Look ma, no built-ins! -1 thanks to ngn.

Since Dyalog APL does not have infinities, I use Iverson's proposed notation.

{1=⍵:'¯'5⍕+/÷⍵*⍨⍳!9}

Try it online!

{ anonymous function:

1=⍵: if the argument is one, then:

  '¯' return a macron

 else

  !9 factorial of nine (362880)

   first that many integers integers

  ⍵*⍨ raise them to the power of the argument

  ÷ reciprocal values

  +/ sum

  5⍕ format with five decimals

} [end of anonymous function]


1
1E6 -> !9­­
ngn

@ngn Thank you.
Adám

5

C, 74 70 69 bytes

n;f(s){double z=n=0;for(;++n>0;)z+=pow(n,-s);printf("%.5f",z/=s!=1);}

Compile with -fwrapv. It will take some time to produce an output.

See it work here. The part ++n>0 is replaced with ++n<999999, so you don't have to wait. This keeps identical functionality and output.


Does float work?
l4m2

5

TI-Basic, 16 bytes (no builtins)

Fix 5:Σ(X^~Ans,X,1,99

You really need to go up to about 150000 to get the answer right for Ans=2, which would take upwards of half an hour to calculate on an 84 Plus CE. Also, you could multiply by (Ans-1)^0 somewhere to get an error for Ans=1, TI-Basic's closest representation of infinity!
pizzapants184

@pizzapants184 I'm fully aware that 2, 3, etc. might take more than 99 iterations. You can achieve this functionality by replacing 99 with E9 where E is the scientific E, i.e. representing 10^9. (Or obviously something smaller like E5). Understanding that E99 is generally used for positive infinity also allows for this functionality theoretically, if the upper bound of the summation was E99. Emulators can provide this much faster than a physical calculator. Thanks for your thoughts :)
Timtech

I don't think this counts as displaying infinity. It won't even throw an error if you added 1 infinitely, due to floating-point imprecision.
lirtosiast

4

C (gcc), 112 101 94 84 bytes

Thanks for the golfing tips from ceilingcat.

n;f(s){float r;for(n=98;n;r+=pow(n--,-s));printf("%.5f",r+pow(99,-s)*(.5+99./--s));}

Try it online!


1
The question has been edited. You can output language native infinity symbols.
2501

@2501 I reverted back to the previous answer, although I'm still quite a few bytes away from your solution.
cleblanc

@ceilingcat f(1) doesn't seem correct.
cleblanc



2

MATL, 21 bytes

q?'%.5f'2e5:G_^sYD}YY

Try it online!

Explanation

Input 1 is special-cased to output inf, which is how MATL displays infinity.

For inputs other than 1, summing the first 2e5 terms suffices to achieve a precision of 5 decimal places. The reason is that, from direct computation, this number of terms suffices for input 2, and for greater exponents the tail of the series is smaller.

q         % Input (implicit) minus 1
?         % If non-zero
  '%.5f'  %   Push string: format specifier
  2e5:    %   Push [1 2 ... 2e5]
  G       %   Push input again
  _       %   Negate
  ^       %   Power. element-wise
  s       %   Sum of array
  YD      %   Format string with sprintf
}         % Else
YY        %   Push infinity
          % End (implicit)
          % Display (implicit)

2

R, 54 bytes

function(a){round(ifelse(a==1,Inf,sum((1:9^6)^-a)),5)}

Finds the sum directly and formats as desired, outputs Inf if a is 1. Summing out to 9^6 appears to be enough to get five-place accuracy while still being testable; 9^9 would get better accuracy in the same length of code. I could get this shorter if R had a proper ternary operator.


1
function(a)round("if"(a-1,sum((1:9^6)^-a)),5) is a few bytes shorter.
Giuseppe

Yes, but it throws an error if a = 1. function(a)round("if"(a-1,sum((1:9^6)^-a),Inf),5) works and is still shorter than my original solution.
Michael Lugo

Oh yes of course! I forgot to include the Inf, that's what I get for typing code into the comment box directly...
Giuseppe

2

C,129 130 128 bytes

#include<math.h>
f(s,n){double r=0;for(n=1;n<999;++n)r+=(n&1?1:-1)*pow(n,-s);s-1?printf("%.5f\n",r/(1-pow(2,1-s))):puts("oo");}

it uses the following formula

\zeta(s) = \frac{1}{1-2^{1-s}}\sum\limits_{n=1}^{\infty}{\frac{(-1)^{n+1}}{n^s}}

test and results

main(){f(2,0);f(1,0);f(3,0);f(4,0);f(8,0);f(19,0);}

1.64493
+oo
1.20206
1.08232
1.00408
1.00000

Why this equation instead of Σ(1/(n^s))? It seems much more complicated...
Beta Decay

@BetaDecay because it seems to me more fast in find the result; here there is the range for sum s in 1..999, in the 'Σ(1/(n^s)) ' there is need s in the range 1..10^6
RosLuP

1
I see. FYI, simply oo is fine, you don't need to specify it as positive
Beta Decay


@ceilingcat you can write one other entry for this question... it seems I remember here without math.h header it not link...
RosLuP

2

Python 3: 67 bytes (no built-ins)

f=lambda a:"∞"if a<2else"%.5f"%sum([m**-a for m in range(1,10**6)])

Nothing fancy, only uses python 3 because of the implicit utf-8 encoding.

Try it online with test cases.


1

Perl 6, 50 bytes

{$_-1??(1..1e6).map(* **-$_).sum.fmt('%.5f')!!∞}


1

Jelly, 23 bytes

ȷ6Rİ*⁸S÷Ị¬$ær5;ḷỊ?”0ẋ4¤

Try it online!

How?

  • Sums the first million terms
  • Divides by 0 when abs(input)<=1 to yield inf (rather than 14.392726722864989) for 1
  • Rounds to 5 decimal places
  • Appends four zeros if abs(result)<=1 to format the 1.0 as 1.00000
  • Prints the result

ȷ6Rİ*⁸S÷Ị¬$ær5;ḷỊ?”0ẋ4¤ - Main link: s
ȷ6                      - literal one million
  R                     - range: [1,2,...,1000000]
   İ                    - inverse (vectorises)
     ⁸                  - link's left argument, s
    *                   - exponentiate
      S                 - sum
          $             - last two links as a monad:
        Ị               -   insignificant? (absolute value of s less than or equal to 1?)
         ¬              -   not (0 when s=1, 1 when s>1)
       ÷                - divide (yielding inf when s=1, no effect when s>1)
           ær5          - round to 10^-5
                      ¤ - nilad followed by link(s) as a nilad:
                  ”0    -   literal '0'
                    ẋ4  -   repeated four times
                Ị?      - if insignificant (absolute value less than or equal to 1?)
              ;         -       concatenate the "0000" (which displays as "1.00000")
               ḷ        - else: left argument
                        - implicit print


0

Jelly, 26 bytes

⁵*5İH+µŒṘḣ7
⁴!Rİ*³Sǵ’ݵ’?

Don't try it online with this link! (Since this uses 16!~20 trillion terms, running on TIO produces a MemoryError)

Try it online with this link instead. (Uses 1 million terms instead. Much more manageable but takes one more byte)

Returns inf for input 1.

Explanation

⁵*5İH+µŒṘḣ7    - format the output number
⁵*5İH+         - add 0.000005
      µŒṘ      - get a string representation
         ḣ7    - trim after the fifth decimal.

⁴!Rİ*³Sǵ’ݵ’? - main link, input s
           µ’? - if input minus 1 is not 0...
⁴!R            -   [1,2,3,...,16!] provides enough terms.
   İ           -   take the inverse of each term
    *³         -   raise each term to the power of s
      S        -   sum all terms
       Ç       -   format with the above link
               - else:
        µ’İ    -   return the reciprocal of the input minus 1 (evaluates to inf)

Out of the 26, bytes, 7 are used for computation, 12 are for formatting, and 7 are for producing inf on zero. There has to be a better golf for this.


ȷ6 is a numeric literal of a million, removing the factorial workaround.
Jonathan Allan

0

MathGolf, 14 bytes (no builtins)

┴¿Å'∞{◄╒▬∩Σ░7<

Note that in the TIO link, I have substituted for , which pushed 106 instead of 107. This is because the version submitted here timeouts for all test cases. This results in the answers for 3 and 8 to be off by 1 decimal place. However, there are way bigger 1-byte numerical literals in MathGolf, allowing for arbitrary decimal precision.

Try it online!

Explanation

┴                check if equal to 1
 ¿               if/else (uses one of the next two characters/blocks in the code)
  Å              start block of length 2
   '∞            push single character "∞"
     {           start block or arbitrary length
      ◄          push 10000000
       ╒         range(1,n+1)
        ▬        pop a, b : push(b**a)
         ∩       pop a : push 1/a (implicit map)
          Σ      sum(list), digit sum(int)
           ░     convert to string (implicit map)
            7    push 7
             <   pop(a, b), push(a<b), slicing for lists/strings

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.