14 Ten wikipedysta edytuje polskojęzyczną Wikibooks od 14 lat, 6 miesięcy i 20 dni.
Obliczono 19 marca 2024.
pl Polski jest językiem ojczystym tego użytkownika.
en-2 This user can read and write intermediate English.




Witam.

Moja strona domowa ( angielska).

Wikipedia - Adam majewski

Commons - Adam majewski


wikibooks edytuj

<syntaxhighlight lang= c>    </syntaxhighlight >

{{Przypisy}}
{{BrClear}} <noinclude>{{Wolumin}}</noinclude>



<noinclude>{{Status|+100%|Astronomia i fizyka|typ=z fizyki|poziom=Studia}}
{{UnikalnaStronaStart
 | nagłówek        = {{Info|Książka wymaga poprawek językowych i stylistycznych.}}
 | nagłówek prawy  = {{Wersja do czytania}}{{Kolekcja}}
 | stopka strony   = {{Kreska nawigacja|{{AktualnaKsiążka}}|{{PierwszyArtykuł}}|{{OstatniArtykuł}}}}
}}</noinclude>


Witaj w polskich Wikibooks! edytuj

Cieszymy się, że udało Ci się do nas dołączyć! Na początek polecamy przydatne strony pomocy:

Poniżej znajdują się dalsze, użyteczne dla użytkownika strony

Śmiało edytuj strony i pamiętaj, że zawsze możesz liczyć na pomoc innych użytkowników.

Chcąc skontaktować się z innym wikipedystą, wpisuj się na stronę jego dyskusji - wtedy dana osoba otrzyma komunikat o wiadomości i będzie mogła Ci odpowiedzieć. Zapraszamy również na IRC-a: #wikibooks-pl. Aktywnych edytujących zobaczysz na ostatnich zmianach. W sprawach projektu dyskutuj w Barze.

Zapoznaj się proszę z Wikibooks:Portal użytkowników i przeczytaj tam wskazane artykuły, aby ten projekt używać zgodnie z wytycznymi. Nie kopiujemy materiałów objętych prawami autorskimi, tzn. nie wstawiamy tu tekstów należących do kogoś bez jego zgody.

Należy sobie przypomnieć, że Wikibooks to miejsce dla otwartych podręczników tworzonych przez Wikipedystów, nie umieszczamy tu informacji o innych książkach.

Przy okazji, jeśli spodobało ci się Wikibooks, poleć nas swoim znajomym - potrzebujemy promocji i rąk do pracy.

Mamy nadzieję, że zostaniesz z nami na dłużej! Odwiedź: Jak przeglądać Wikibooks,a także: Zasady i wskazówki, by skutecznie samemu lub z pomocą innych, rozwiązywać swoje problemy na tym serwisie! Mamy nadzieję, że zostaniesz z nami na dłużej! Wcelu poznania niektórych mechanizmów składni MediaWiki możesz bez edycji kliknąć edytuj, podejrzeć, i kliknąć ponownie moduł.

kategorie edytuj

Kategorie na Wikibooks mają nieco inne użycie niż na Wikipedii. Na Wikipedii każda strona znajduje się w jakiejś kategorii; na Wikibooks to podręczniki są podstawowymi jednostkami i tylko stronę główną podręcznika (okładkę, a wobec jej braku spis treści) umieszcza się w określonej kategorii. Podręcznik dopasujesz do odpowiedniej kategorii, przeglądając Kategoria:Podręczniki według tematu.

Wykaz ważnych stron "technicznych", "administracyjnych" i ogólnej natury znajdziesz w kategorii: meta-strony Wikibooks.

Błędnym postępowaniem jest także tworzenie podkategorii dla podręczników językowych. Dlatego też, np. podręcznik do języka niemieckiego powinien znajdować się tylko w kategorii "Języki". Nie należy więc wstawiać w modułach tego podręcznika kategorii "Język niemiecki" i ją osobno tworzyć. Podobnie nie powinno się tworzyć oddzielnych podkategorii "Język portugalski", "Język rumuński" itp.

Wstawiając komendę [[Kategoria:...]], na okładce należy ją obudować komendą "noinclude", np.

<noinclude>
[[Kategoria:Języki]]
</noinclude>

Dzięki temu unikniemy problemów z tworzeniem wersji do druku.

mediawiki edytuj

MediaWiki is a software (wiki engine software) for Wikipedia and the other Wikimedia projects

book features edytuj

  • level
  • status
  • topic

hierarchy edytuj

Hierarchy

Or

  • collection

See also

collection edytuj

At one time they could also be:

  • rendered as PDF (see PDF Writer)
  • exported as ODF Text Document (see OpenDocument Export)
  • exported as DocBook XML (see XML Bridge)
  • exported as ZIM file (see openZIM)
  • exported as ePub file (ebook)

other edytuj

{{wikipedia|Object Pascal}}
{{wikipedia|Pascal (język programowania)}}

{{TODO|Dodać jakiś przykład użycia.}}
<syntaxhighlight lang="c">  </syntaxhighlight>

Przydatne linki

admin - import

spr. - NPA


Szablon {{Wolumin}} edytuj

 
Wikipedia-kategoyzacja schemat

A nie lepiej użyć szablon {{Wolumin}}, a nie [[Kategoria:Książka:C]], tak jest prostszej.

Wystarczy napisać na stronie końca artykułu:

{{BrClear}} <noinclude>{{Wolumin}}</noinclude>


Jeżeli wstawiłeś na stronę książki C, to wystarczy to ona zwróci kategorię: Książka:C, co jest równoważne kodowi: [[Kategoria:Książka:C]].


A w przypadku stron artykułów, to są: Spis treści w sekcji dotyczącej kategorii. Przeczytaj tam wspomnianą stronę i jego podstrony: Wikibooks:Szablony. Szablony: {{Kategoria}} (patrz dokumentacja) - dodawanie pojedynczych kategorii, {{Kategorie}} (patrz dokumentacja) - dodawanie zbioru kategorii. Szablon {{Status}} - wstawiany zwykle na strony główne podręczników, ewentualnie dodaje do tej strony kategorię książkową, w przypadku tego podręcznika, to będzie ta sama kategoria, jak dla innych artykułów, na stronie głównej książki używany szablonu {{Status}} (patrz dokumentacja), a na innych artykułach {{Wolumin}} (patrz dokumentacja). Szablony liczb: {{Łączna liczba stron w kategoriach}} (patrz dokumentacja) - liczy nierekurencyjnie liczbę stron w kategoriach, a {{Rekurencyjna łączna liczba stron w kategoriach}} (patrz dokumentacja) - liczy rekurencyjnie liczbę stron w kategoriach. Szablon {{OpakujKategorie}} (patrz dokumentacja) - opakowuje kategorie, zwykle bez nazw sortowania, w ramkę i nie umieszcza ich na samej dole strony, tylko w tej ramce, {{OpakujKategorieZeSortowaniem}} (patrz dokumentacja) - opakowuje kategorie wraz z ich nazwami sortowania.



Na Wikibooksie nie używamy zapisu: [[Kategoria:Nazwa kategorii]] lub [[Kategoria:Nazwa kategorii|nazwa sortowania]], tylko zamiast tego używamy te szablony wspomniane wcześniej, ze względu na kontrolę ich z jednego miejsca, np. jakaś kategoria nie istnieje, to jest wtedy łatwo, to naprawić, w przypadku systemowych wywołań jest trudno, w szablonach od zwracania kategorii: {{Status}}, {{Wolumin}}, {{Kategoria}} i {{Kategorie}}, mają w sobie ukryte te wywołania systemowe w swojej budowie, łatwo to sprawdzić wywołując: {{Nowiki|{{Wolumin}}}}. Szablony kategorii domyślnie dodają sortowanie kategorii, więc nie trzeba sortować wszystkich kategorii razem wziętych bez sortowania według: {{DEFAULTSORT:Nazwa sortowania}}.


Możesz poczytać artykuł na Wikipedii: Kategorie.

Przypisy bibliograficzne i rzeczowe edytuj

Jak używasz przypisów bibliograficznych, użyj:

== Przypisy ==
{{Przypisy}}

W przypadku uwag, przypisów rzeczowych:

== Uwagi ==
{{Uwagi}}

Szablony pomocnicze: {{r}} - do przypisów bibliograficznych, i {{u}} - do przypisów rzeczowych (uwag): szablony, że tutaj używamy przypisów jako jego wskazania, ale jako referencję bez definicji, oraz {{Ref}} - definicja przypisów we wnętrzu szablonów {{Przypisy}}, {{Uwagi}} i {{Przypisy-lista}}, jako ich parametry, wskazanych przez te dwa pierwsze szablony. Za pomocą szablonu {{Ref}} możemy wskazać definicję referencji w tekście, a na samym końcu używamy, któreś z trzech szablonów, ale tym razem bez parametrów, a nie z parametrami.


Szablony do innych przypisów wielokolumnowych, ale bibliograficznych:

== Przypisy ==
{{Przypisy-lista}}

nie używamy = Poziomu 1 = w artykułach ( wikipedia)

Szablony nawigacji edytuj

A jak używasz nawigacji, to użyj szablonów stronicowych, nawigacja na Wikibooksie, w książkach jest do poprawienia. Zobacz dokumentację szablonu {{AktualnaKsiążka}}, a tam są przykłady szablonów stronicowych dla nawigacji. Jeśli używasz szablonu {{Autonawigacja}}, to użyj tego szablonu, przykłady w dokumentacji jeszcze nieukończonej, ale to wystarczy dla książek, w nich artykułów.

komputer edytuj

  • obudowa ( ang, case)[1]
    • Small Form Factor (SFF)
    • Mini-Tower
    • Mid-Tower
    • Full-Tower 20 inches (51 cm) or more in height,


Motherboard

  • Intel DB85FL Version: AAG89861-201 Serial Number: BQFL32200073 , with Intel® B85 Chipset,
  • GPU : NVIDIA Corporation GK104 [GeForce GTX 770] (rev a1)

Lista sprzętu

NVIDIA GeForce GTX 770 1.2.175 470.161.3.0 2022-12-11 06:01:22 1

wayland edytuj

binary tree edytuj

wizualizacja


// https://gitlab.com/nikita_karatun/algorithms_in_cpp/-/blob/master/box_drawing_chars.h?ref_type=heads
#include <string>

namespace Box_drawing_chars {
    const char* h_line = "─";
    const char* v_line = "│";

    const char* right_top = "└";
    const char* left_top = "┘";
    const char* right_bottom = "┌";
    const char* left_bottom = "┐";

    const char* right_t = "├";
    const char* left_t = "┤";
    const char* top_t = "┴";
    const char* bottom_t = "┬";
    const char* cross = "┼";
}
#                 +---+                 
#        +--------| * |-------+         
#        |        +---+       |         
#      +---+                +---+       
#   +--| + |--+          +--| + |--+    
#   |  +---+  |          |  +---+  |    
# +---+     +---+      +---+     +---+  
# | 2 |     | 2 |      | 4 |     | 5 |  
# +---+     +---+      +---+     +---+  


-- Vertically centered textual tree using UTF8 monospaced
-- box-drawing characters, with options for compacting
-- and pruning.

--               ┌── Gamma 
--       ┌─ Beta ┼── Delta 
--       │       └ Epsilon 
-- Alpha ┼─ Zeta ───── Eta 
--       │       ┌─── Iota 
--       └ Theta ┼── Kappa 
--               └─ Lambda 
(NB – view in mono-spaced font)


Compacted (not all parents vertically centered):

       ┌ 4 ─ 7 
   ┌ 2 ┴ 5 
 1 ┤       ┌ 8 
   └ 3 ─ 6 ┴ 9 

Fully expanded and vertically centered:

               ┌── Gamma 
               │
       ┌─ Beta ┼── Delta 
       │       │
       │       └ Epsilon 
       │
 Alpha ┼─ Zeta ───── Eta 
       │
       │       ┌─── Iota 
       │       │
       └ Theta ┼── Kappa 
               │
               └─ Lambda 

Vertically centered, with nodeless lines pruned out:

               ┌── Gamma 
       ┌─ Beta ┼── Delta 
       │       └ Epsilon 
 Alpha ┼─ Zeta ───── Eta 
       │       ┌─── Iota 
       └ Theta ┼── Kappa 
               └─ Lambda 
--8
  `--8
     |--7
     |  |--3
     |  |  |--2
     |  |  |  `--2
     |  |  |     `--2
     |  |  |        |--1
     |  |  |        `--1
     |  |  `--1
     |  |--2
     |  |  |--1
     |  |  `--1
     |  |--1
     |  `--1
     `--1
--1
  |--2
  |  |--4
  |  |  |--7
  |  |  |  |-- (null)
  |  |  |  `-- (null)
  |  |  `-- (null)
  |  `--5
  |     |-- (null)
  |     `-- (null)
  `--3
     |--6
     |  |--8
     |  |  |-- (null)
     |  |  `-- (null)
     |  `--9
     |     |-- (null)
     |     `-- (null)
     `-- (null)

video edytuj

https://fractalforums.org/mandelbulb3d/13/creating-a-video/4958/msg36079#new


ffmpeg -framerate 60 -r 60 -i image%06d.png -pix_fmt yuv420p -profile:v high -level:v 4.1 -crf:v 20 -movflags +faststart output.mp4
  • for other than 60 fps, change framerate and r
  • input is image000001.png, image000002.png, ... , %06d means a zero-padded number with six digits, change if your input images are named differently
  • -pix_fmt yuv420p is required for compatibility with most players (default is yuv444 or maybe even rgb, which most players don't handle well if at all)
  • -profile:v, -level:v also control compatibility settings, 4k probably needs a higher level setting
  • -crf:v is the quality-vs-size control, lower numbers are higher quality larger file size, higher numbers are lower quality smaller file size, crf 20 is pretty high quality, iirc changing by 6 affects the file size by a factor of 2
  • -movflags +faststart is required for streaming (otherwise the whole file has to be downloaded before playback can start)
  • ffmpeg can also add/encode a soundtrack if you want one

błędy w obliczeniach numerychnych edytuj

Avoiding loss of significance edytuj

Although the quadratic formula provides an exact solution, the result is not exact if real numbers are approximated during the computation, as usual in numerical analysis, where real numbers are approximated by floating point numbers (called "reals" in many programming languages). In this context, the quadratic formula is not completely stable.

This occurs when the roots have different order of magnitude, or, equivalently, when b2 and b2 − 4ac are close in magnitude. In this case, the subtraction of two nearly equal numbers will cause loss of significance or catastrophic cancellation in the smaller root. To avoid this, the root that is smaller in magnitude, r, can be computed as   where R is the root that is bigger in magnitude.

A second form of cancellation can occur between the terms b2 and 4ac of the discriminant, that is when the two roots are very close. This can lead to loss of up to half of correct significant figures in the roots.[2][3]



https://coral.ie.lehigh.edu/~ted/files/ie496/lectures/Lecture20.pdf


Roots of a quadratic (ax2 + bx + c)

If x1 ≈ 0 and x2 >> 0, then the quadratic formula is unstable.

Computing x2 by the quadratic formula and then setting x1 = cx2 / a is stable.

Przykład 2 edytuj

Innym przykładem na to, że nawet najprostsze algorytmy mogą być źle uwarunkowane jest „szkolny” algorytm obliczania pierwiastków równania kwadratowego

 
 

W sposobie obliczenia jednego z pierwiastków jest odejmowanie. Możliwa jest sytuacja, w której wartość   i   mogą być dość bliskie zeru co do modułu - nastąpi utrata cyfr znaczących.

Rozwiązanie Sposobem na ominięcie tego problemu mogą być Wzory Viète’a - dobrze uwarunkowany pierwiastek może być obliczony „wprost”, drugi otrzymany ze wzoru Viète’a. Należy również zauważyć, że możemy mieć tutaj tutaj do czynienia z dwoma przypadkami tj. b>=0 oraz b<0. Dla pierwszego przypadku dobrze uwarunkowanym będzie pierwiastek pierwszy, a dla drugiego przypadku dobrze uwarunkowanym będzie pierwiastek drugi.

Instability of the quadratic equation edytuj

For example, consider the quadratic equation

 

with the two exact solutions:

 

This formula may not always produce an accurate result. For example, when   is very small, loss of significance can occur in either of the root calculations, depending on the sign of  .

The case  ,  ,   will serve to illustrate the problem:

 

We have

 

In real arithmetic, the roots are

 
 

In 10-digit floating-point arithmetic:

 
 

Notice that the solution of greater magnitude is accurate to ten digits, but the first nonzero digit of the solution of lesser magnitude is wrong.

Because of the subtraction that occurs in the quadratic equation, it does not constitute a stable algorithm to calculate the two roots.

A better algorithm edytuj

A careful floating-point computer implementation combines several strategies to produce a robust result. Assuming that the discriminant b2 − 4ac is positive, and b is nonzero, the computation would be as follows:[4]

 

Here sgn denotes the sign function, where   is 1 if   is positive, and −1 if   is negative. This avoids cancellation problems between   and the square root of the discriminant by ensuring that only numbers of the same sign are added.

To illustrate the instability of the standard quadratic formula compared this formula, consider a quadratic equation with roots   and  . To 16 significant digits, roughly corresponding to double-precision accuracy on a computer, the monic quadratic equation with these roots may be written as

 

Using the standard quadratic formula and maintaining 16 significant digits at each step, the standard quadratic formula yields

 
 
 

Note how cancellation has resulted in   being computed to only 8 significant digits of accuracy.

The variant formula presented here, however, yields the following:

 
 

Note the retention of all significant digits for  .

Note that while the above formulation avoids catastrophic cancellation between   and  , there remains a form of cancellation between the terms   and   of the discriminant, which can still lead to loss of up to half of correct significant digits.[2][3] The discriminant   needs to be computed in arithmetic of twice the precision of the result to avoid this (e.g. quad precision if the final result is to be accurate to full double precision).[5] This can be in the form of a fused multiply-add operation.[2]

To illustrate this, consider the following quadratic equation, adapted from Kahan (2004):[2]

 

This equation has   and roots

 
 

However, when computed using IEEE 754 double-precision arithmetic corresponding to 15 to 17 significant digits of accuracy,   is rounded to 0.0, and the computed roots are

 
 

which are both false after the 8-th significant digit. This is despite the fact that superficially, the problem seems to require only 11 significant digits of accuracy for its solution.

Przydatne strony edytuj

(Skopiowałem ze strony Karola Dąbrowskiego)



  • <syntaxhighlight lang="c">...</syntaxhighlight>

http://www.theiterators.com/technologies/

zunzun

git add edytuj

git add is a multipurpose command – you use it to begin tracking new files, to stage files, and to do other things like marking merge-conflicted files as resolved. I

git patch edytuj

How to contribute your changes (bug fixes, new features, ...):

git checkout master git pull git checkout -b my-new-stuff

  1. edit files, make changes

git add your-changed-files git commit

  1. write a short description, the first line is the most important

git format-patch master

  1. then email the patches as attachments

Try to split each distinct set of changes into different commits (eg: a bug fix in one file and a new feature in another file should be two commits). On the other hand, changes in multiple files for the same bug-fix or feature should be in one commit. Make sure it compiles before you commit, and preferably make sure it runs and does the right things without breaking other stuff.

Alternatively to git format-patch and emailing, make your repository available online. https://gitorious.org has tools for forking repositories and submitting merge requests, though I've not used them much so can't offer any tips.

c edytuj

c= 1/4
zf= z = 0.499999996905453  +0.000000000000000 i
z = 0.503446319355695  +0.000195822466591 i
z = 0.501859335396733  +0.000051833858094 i
z = 0.504519704479711  +0.000098150630449 i

trygonometria edytuj

 

#define radian2degree(r) (r * 57.295779513082) // r*180/pi = r* 57.295779513082
#define degree2radian(d) (d * 0.017453292519)  //  d*pi/180 = d*0.017453292519

double radians_to_degrees(double rad)
{
  return rad * 180.0 / M_PI;
}

double degrees_to_radians(double deg)
{
  return deg * M_PI / 180.0;
}

//
angle1 = angle1/(2.0*M_PI); // from radians to turns
//
// conversion of the output of atan2 function to input of cs and sin functions 
double angle1 = M_PI + atan2(cimag(Z0) - cimag(Z1), creal(Z0) - creal(Z1)); //  radians from range [-pi,pi] to range [0,2 pi]
double x = creal(Z0) +  (radius + dr) *  cos(angle1);
double y = cimag(Z0) +  (radius + dr) *  sin(angle1);
complex double Z1new = x+y*I;

funkcje edytuj

  • aint(x) returns the integral value between x and 0, nearest x.
  • anint(x) returns the nearest integral value to x, except halfway cases are rounded to the integral value larger in magnitude.
  • Nearest Integer Function = nint(x) converts x into int format rounding to the nearest int value, except halfway cases are rounded to the int value larger in magnitude.


plik edytuj

dwa podstawowe mechanizmy połączenia między programem a plikiem ( oraz z urządzeniem takim jak terminal lub potokiem lub gniazdem do komunikacji z innym procesem): [6]

  • deskryptory plików ( ang. file Descriptors). Deskryptory plików są reprezentowane jako obiekty typu int. Deskryptory plików zapewniają prymitywny, niskopoziomowy interfejs do operacji wejścia i wyjścia.
  • strumienie ( ang. stream). Strumienie są reprezentowane jako obiekty FILE *.


róznice edytuj

  • plik ( dane na plik na dysku)
    • file descriptor
    • file pointer
  • strumień ( przepływ danych)
  • bufor ( miejsce w pmięci)
  • wskażnik ( adres pamięci)


Pojęcia są związane ze sobą ale mają inne znaczenie (określają różne rzeczy )[7]

strumienie edytuj

Strumień ( ang stream) jest to termin o szerokim i zmiennym znaczeniu ( ang. a loose term) [8]

  • zwykle oznacza ciąg o nieokreślonej długości
    • Długość może być nieznana nawet nadawcy. Weźmy na przykład zadanie tworzenia strumienia w locie, prawdopodobnie z innych strumieni. Strumień może być nawet nieskończenie długi. Czasami długość strumienia jest znana, ale po prostu jest ignorowana. Czasami długość jest znana, ale nie w jednostkach użytkowych. Program odczytujący wiersze o zmiennej długości ze strumienia prawdopodobnie nie może zrobić nic użytecznego z długością strumienia w bajtach.
    • pojęcie to jest używane w komunikacji w odniesieniu do danych przekazywanych między autorem/nadawcą/producentem a czytelnikiem/odbiorcą/konsumentem
    • dostęp do strumienia jest sekwencyjny, niezależnie od tego, czy jest to konieczne, czy wygodne. Możliwość przeskoczenia do innego miejsca w strumieniu nie dyskwalifikuje automatycznie użycia tego terminu.
  • reprezentacja przepływu danych z jednej strony na drugą, np. z dysku do pamięci i z pamięci na dysk[9]. Użycie strumieni pozwala przesyłać duże ilości dane, w taki sposób aby nie zabrakło pamięci. [10]
  • w Biblioteki Standardowej C ( ang. the C Standard Library ) strumień jest ogólnym interfejsem do wykonywania pewnych operacji wejścia i wyjścia( ang. I/O operations ).
    • Ze względów historycznych typ struktury danych C reprezentujący strumień nosi nazwę PLIK ( ang. FILE), a nie „strumień”. Ponieważ większość funkcji bibliotecznych dotyczy obiektów typu FILE*, czasami termin wskaźnik pliku jest również używany w znaczeniu „strumień”. Prowadzi to do niefortunnego zamieszania w terminologii w wielu książkach na temat C[11]




Stream (disambiguation) - Computing and technology edytuj


Strumień (ujednoznacznienie) - Informatyka i technologia

  • Strumień danych: sekwencja elementów danych udostępnionych w czasie
  • graficzna reprezentacja przepływów
  • wstępnie połączone strumienie wejściowe i wyjściowe dla programów komputerowych
  • Przetwarzanie strumieniowe ,
  • paradygmat programowania komputerowego
  • Media strumieniowe , multimedia przesyłane strumieniowo do użytkownika końcowego .stream , ogólna domena najwyższego poziomu przeznaczona do przesyłania strumieniowego witryny medialne Transmisja strumieniowa na żywo,
  • transmisja mediów w czasie rzeczywistym do widza Usługi strumieniowe,
  • Platformy strumieniowelista platform strumieniowych opartych na subskrypcji
  • STREAM konwencja pomiaru przepustowości pamięci i test porównawczy
  • STREAMS - framework Unix System V

typy edytuj

strumienie w C:

tablice edytuj

  • typ
    • statyczne (
    • dynamiczne (
  • wymiar
    • jednowymiarowe (1D , wektor)
    • dwuwymiarowe ( 2D , macierz , ang. matrix)
      • wielowymiarowe
  • operacje na tablicach
    • deklaracja
    • initializacja
    • użycie
    • usunięcie
  • ???
    • Flexible array member =
    • variable-length array = VLA, runtime-sized

analiza programu w języku Haskell edytuj

-- Haskell code by Claude Heiland-Allen
-- http://mathr.co.uk/blog/

import Control.Monad (forM_)
import Data.List (genericTake, genericDrop, intercalate)
import Data.Fixed (mod')
import Data.Ratio ((%), numerator, denominator)
import Numeric (readInt)
import System.Environment (getArgs)

type InternalAngle = Rational

type ExternalAngle = ([Bool], [Bool])

pretty :: ExternalAngle -> String
pretty (pre, per) =  bits pre ++ "(" ++ bits per ++")"

bits :: [Bool] -> String
bits = map bit

bit :: Bool -> Char
bit False = '0'
bit True = '1'

binary :: [Bool] -> Integer
binary [] = 0
binary s = case readInt 2 (`elem`"01") (\c -> case c of '0' -> 0 ; '1' -> 1) (bits s) of
  [(b, "")] -> b

rational :: ExternalAngle -> Rational
rational (pre, per) = (binary pre % 2^p) + (binary per % (2^p * (2^q - 1)))
  where
    p = length pre
    q = length per

bulb :: InternalAngle -> (ExternalAngle, ExternalAngle)
bulb pq = (([], bs ++ [False, True]), ([], bs ++ [True, False]))
  where
    q = denominator pq
    bs
      = genericTake (q - 2)
      . map (\x -> 1 - pq < x && x < 1)
      . iterate (\x -> (x + pq) `mod'` 1)
      $ pq

hub :: InternalAngle -> [ExternalAngle]
hub pq =
  [ (sm, shift k sp) | k <- [0, b .. (q - p - 1) * b] ] ++
  [ (sp, shift k sp) | k <- [(q - p) * b, (q - p + 1) * b .. (q - 1) * b] ]
  where
    p = numerator pq
    q = denominator pq
    (([], sm), ([], sp)) = bulb pq
    (ab, cd) = parents pq
    b = denominator ab
    shift k = genericTake q . genericDrop k . cycle -- 

parents :: InternalAngle -> (InternalAngle, InternalAngle)
parents pq = go q 1 0 p 0 1
  where
    p = numerator pq
    q = denominator pq
    go r1 s1 t1 r0 s0 t0
      | r0 == 0 =
          let ab = - s1 % t1
              a = numerator ab
              b = denominator ab
              c = p - a
              d = q - b
              cd = c % d
          in  (min ab cd, max ab cd)
      | otherwise =
          let (o, r) = divMod r1 r0
              s = s1 - o * s0
              t = t1 - o * t0
          in  go r0 s0 t0 r s t

main :: IO ()
main = do
  [sp, sq] <- getArgs
  p <- readIO sp
  q <- readIO sq
  let pq = p % q
      (lo, hi) = bulb pq
      hs = hub pq
  putStrLn $ "internal angle p/q = " ++ sp ++ " / " ++ sq 
  putStrLn $ "internal angle in lowest terms = "
  print pq
  putStrLn $ "rays of the bulb:"
  putStrLn $ pretty lo ++ " = " ++ show (rational lo)
  putStrLn $ pretty hi ++ " = " ++ show (rational hi)
  putStrLn $ ""
  putStrLn $ "rays of the hub:"
  forM_ hs $ \h -> putStrLn $ pretty h  --- ++ " = " ++ show (rational h)

Grafiken zeichnen edytuj

Für das Zeichnen von Grafiken wird hier das Modul matplotlib verwendet. matplotlib ist ein externes Modul und muss vor der ersten Verwendung installiert werden. Das geht so:

  1. Starten Sie ein Terminal (bei Windows die Eingabeaufforderung).
  2. Führen Sie darin folgenden Befehl aus c:\devel\Python\Scripts\pip.exe install matplotlib

pip ist übrigens der Paketmanager von Python ( Pip_(Python) ).

Optimalerweise installieren wir auch gleich das Modul numpy (Numerical Python). Wir werden es im Folgenden oft benötigen (nicht nur bei den Grafiken). Das funktioniert vom Prinzip her genauso, wie für matplotlib gezeigt.

2D edytuj

Graph einer Funktion edytuj

Es soll die cosh-Funktion im Intervall   gezeichnet werden. Der Programmcode lautet in der einfachsten Form:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-3., 3.1, .1)
y = np.cosh(x)

plt.plot(x,y)
plt.grid()
plt.show()

Ausgabe:

Datei:PythonIng_cosh1.jpg

Der Code ist quasi selbsterklärend. Das Untermodul pyplot des matplotlib-Moduls und das numpy-Modul werden importiert. x läuft von -3 bis +3. y wird für jeden x-Wert per Formel ausgerechnet. "plt.plot()" ist der Zeichenbefehl. "plt.show" ist notwendig, um das Fenster mit der Grafik anzuzeigen. Die Schrittweite 0.1 wurde so gewählt, um einen ausreichend glatten Verlauf des Graphen zu gewährleisten. Das ist immer ein Kompromiss zwischen Berechnungszeit und Ansehnlichkeit. Testen Sie einfach ein paar verschiedene Werte, um ein Gefühl dafür zu zu bekommen. "plt.grid()" zeichnet ein Gitter in die Grafik (kann auch weggelassen werden). Die Bezeichnungen plt und np könnten auch anders gewählt werden. Es ist aber Konvention, diese so wie hier gezeigt zu wählen.

Ein etwas komplexeres Beispiel ist Folgendes:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-3., 3.1, .1)
y = np.cosh(x) + 2**x

plt.plot(x,y)
plt.grid()
plt.show()

Man beachte, dass im Gegensatz zu Octave und Julia der ominöse Punkt (.) bei 2**x mit Python nicht benötigt wird. Das macht das Programmiererleben etwas einfacher.

Graphen mehrerer Funktionen und weiteres edytuj

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-3., 3.1, .1)
y1 = np.cosh(x) + 2**x
y2 = np.sin(x) * np.cos(x)

plt.plot(x, y1, label = "cosh(x) + 2**x")
plt.plot(x, y2, label = "sin(x) * cos(x)")
plt.grid()
plt.title("Funktionsgraphen")
plt.xlabel("x")
plt.ylabel("y")
plt.legend(loc="best")

plt.show()

Datei:PythonIng_cosh2.png

Um die Linienstile etwas individueller zu gestalten, ist folgender Programmcode gedacht:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-3., 3.1, .1)
y1 = np.cosh(x) + 2**x
y2 = np.sin(x) * np.cos(x)

plt.plot(x, y1, label = "cosh(x) + 2**x", lw=5, ls="dotted")
plt.plot(x, y2, label = "sin(x) * cos(x)", lw=3, ls="--")
plt.grid()
plt.title("Funktionsgraphen")
plt.xlabel("x")
plt.ylabel("y")
plt.legend(loc="best")

plt.show()

Datei:PythonIng_cosh3.png

Funktion in Parameterdarstellung edytuj

Es soll die archimedische Spirale   im Intervall   gezeichnet werden.

import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0., 6*np.pi, .1)
x = t * np.cos(t)
y = t * np.sin(t)

plt.plot(x, y)
plt.grid()
plt.title("Archimedische Spirale")
 
plt.show()

Datei:PythonIng_spirale1.png

Diese Darstellung erscheint verzerrt. Will man gleiche Achsenskalierungen, so kann man den plt.axis()-Befehl verwenden.

import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0., 6*np.pi, .1)
x = t * np.cos(t)
y = t * np.sin(t)

plt.plot(x, y)
plt.grid()
plt.title("Archimedische Spirale")
plt.axis("equal")

plt.show()

Datei:PythonIng_spirale2.png

Logarithmische Achsenskalierung edytuj

Aufgaben edytuj

  • Zeichnen Sie die Strophoide  . Das Ganze sollte in etwa so aussehen wie folgende Grafik:

Datei:octave_strophoide.jpg

  • Zeichnen Sie die verschlungene Hypozykloide  . Das Ganze sollte in etwa so aussehen wie folgende Grafik:

Datei:octave_hypozykloide.jpg

  • Testen Sie bei den obigen Übungsaufgaben verschiedene Linienstile und Farben. Farben können mit dem plt.plot()-Parameter color gewählt werden.
  • Testen Sie bei den obigen Übungsaufgaben verschiedene Werte für a, c, r und R.

3D edytuj

Räumliche Kurven edytuj

import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0, 6*np.pi, 0.1)
x = t * np.cos(t)
y = t * np.sin(t)
z = t

fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax.plot(x, y, z)

plt.show()

Datei:PythonIng_raumkurve1.png

Flächen edytuj

import matplotlib.pyplot as plt
import numpy as np 

x = np.arange(0, 10, 0.1)
y = np.arange(0, 10, 0.1)
x, y = np.meshgrid(x, y)
z = np.sin(x) + 3 * np.cos(y)

fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax.plot_surface(x, y, z)

plt.show()

Datei:PythonIng_fläche1.png

Das Ganze in Netzdarstellung läßt sich so programmieren:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10, 0.5)
y = np.arange(0, 10, 0.5)
x, y = np.meshgrid(x, y)
z = np.sin(x) + 3 * np.cos(y)

fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax.plot_wireframe(x, y, z)

plt.show()

Datei:PythonIng_fläche2.png

Höhenlinien edytuj

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10, 0.1)
y = np.arange(0, 10, 0.1)
x, y = np.meshgrid(x, y)
z = np.sin(x) + 3 * np.cos(y)

fig, ax = plt.subplots()
ax.contour(x, y, z)

plt.show()

Datei:PythonIng_höhenlinien1.png

Etwas abgewandelt sind das so aus:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10, 0.1)
y = np.arange(0, 10, 0.1)
x, y = np.meshgrid(x, y)
z = np.sin(x) + 3 * np.cos(y)

fig, ax = plt.subplots()
hl = ax.contour(x, y, z)
ax.clabel(hl, inline = True)

plt.show()

Datei:PythonIng_höhenlinien2.png

Aufgaben edytuj

  • Zeichnen Sie die räumliche Kurve  ,  ,  ,  .
  • Zeichnen Sie die Fläche  .

Animationen edytuj

Przypisy