segunda-feira, 25 de novembro de 2013

Math for what...! Fast inverse square root.

From wiki: Fast inverse square root (sometimes referred to as Fast InvSqrt() or by the hexadecimal constant 0x5f3759df) is a method of calculating x−½, the reciprocal (or multiplicative inverse) of a square root for a 32-bit floating point number in IEEE 754 floating point format. The algorithm was probably developed at Silicon Graphics in the early 1990s, and an implementation appeared in 1999 in the Quake III Arena source code, but the method did not appear on public forums such as Usenet until 2002 or 2003.[1] At the time, the primary advantage of the algorithm came from avoiding computationally expensive floating point operations in favor of integer operations. Inverse square roots are used to compute angles of incidence and reflection for lighting and shading in computer graphics.
The algorithm accepts a 32-bit floating point number as the input and stores a halved value for later use. Then, treating the bits representing the floating point number as a 32-bit integer, a logical shift right of one bit is performed and the result subtracted from the "magic" value 0x5f3759df. This is the first approximation of the inverse square root of the input. Treating the bits again as floating point it runs one iteration of Newton's method to return a more precise approximation. This computes an approximation of the inverse square root of a floating point number approximately four times faster than floating point division.

domingo, 24 de novembro de 2013

Wolframalpha

Como resolver e plotar equações difíceis e simples no http://www.wolframalpha.com/input/?i=xx+-2
 Note que a equação x² - 2 tem como raiz positiva raiz quadrada de 2, clique no link acima e veja no gráfico como a parábola intercepta o eixo x exatamente no ponto x = raiz quadrada de 2.

How to solve and plot difficult and simple equations in  http://www.wolframalpha.com/input/?i=xx+-2. Note that the equation x ² - 2 has the positive root square root of 2, click the link above to see the chart as the parabola intersects the x-axis exactly at the point x = square root of 2.

Pythagorean theorem without formulas, you believe everything they tell you? Take the test! =) Part 1

This is the first publication to do regarding education. Present a java code that performs the calculation of the distance between two points , in this case, the points that form the hypotenuse of an isosceles right triangle with sides 1.1 , hypotenuse ( hip ) . If we did this procedure with a school rule would have a very inaccurate 1.4 cm and our eyes perceive value a bit more to improve our accuracy , we can make a proportionally larger triangle . If we did 10x , ie 10,10,10 * hip sides would have to answer 10 * higher , however , our rule now gives the value of 14.1 cm and again our eyes leave us in doubt . 100x greater if we did we can assume that the value would be 141.4 cm . Try it yourself. There is a statement that says that if we would have the perfectly precise calculation of the amount equivalent to the value of the hypotenuse square 2 ( 1.4142135623730950 ... ) root , note that the initial idea I had to measure with a ruler was giving us values increasingly accurate. I had the idea to make a program in java that utilizes methods for drawing lines and points . I made the triangle with sides 1.1 , and calculating the hypotenuse has great need 1.4142135623730951 error with only the last digit (1) when compared with the calculation made by other more accurate methods continue to ... 0488016887242097 ... therefore the program also has its limitations but let's assume that this approximation to have the value of two as the same squared value is approximately 2.0000000000000001 . But recently I discovered that montássemos a triangle of sides 1 , square root of 2 , hypotenuse , we would have the amazing value of the square root of 3 as shown in the link ( http://www.geom.uiuc.edu/ ~ demo5337 / Group3/spiral.gif ) . In the figure, one side of all other triangles has written value, but it is equal to 1 , namely sides 1, 1, to the first quarter . For one second sides , a, b (note that a = 2 and b = root root 3) and so on successively . The code below will show my algorithm . If you want to run the code just copy it to a java IDE ( Eclipse or Netbeans for ex.) . But some outlets already advance : programmed to never stop until at least not burst where the program memory. The first part confinement here , part 2 will include graphics.
raiz de 1 1.0
raiz de 2 1.4142135623730951
raiz de 3 1.7320508075688774
raiz de 4 2.0
raiz de 5 2.23606797749979
raiz de 6 2.4494897427831783
raiz de 7 2.6457513110645907
raiz de 8 2.8284271247461903
raiz de 9 3.0000000000000004
raiz de 10 3.16227766016838
<?java


import java.awt.*;
import java.applet.*;
import java.awt.geom.*;

public class Line2D1 extends Applet {

    private Line2D Shape1;
    private Line2D Shape2;
    private Line2D Shape3;
    private Line2D iShape;
    //double diagonal;
    private Point2D Point1;
    private Point2D iPoint;
    double raizquadrada;
    boolean continua = true;

    public static void main(String[] args) {
        Line2D1 mede = new Line2D1();
        mede.raiziterativa();
        
    }

    public void raiziterativa() {

        boolean continua = true;

        while (continua == true) {
            iPoint = new Point2D.Double(0, raizquadrada);
            raizquadrada = iPoint.distance(Shape1.getP2());
            iShape = new Line2D.Double(Shape1.getP1(), iPoint);
            long i;
            i = Math.round(Math.pow(raizquadrada, 2)) ;

            System.out.println("raiz de " + i + " " + raizquadrada);
        }

    }

    public Line2D1() {
        Shape1 = new Line2D.Double(0, 0, 1, 0); // linha vertical vetor da esqPdir
        //Shape2 = new Line2D.Double();
        //Shape2.setLine(0.F, 0.F, 0.F, 1.F); // linha horizontal vetor de cimaPbaixo cpb
        //Shape3 = new Line2D.Double(120, 0, 20, 100); // diagonal cpb dpe.
        Point1 = new Point2D.Double(0, 1);
        Shape2 = new Line2D.Double(Shape1.getP1(), Point1);
        Shape3 = new Line2D.Double(Shape1.getP2(), Point1);

    }

    @Override
    public void paint(Graphics g) {
        Graphics2D g2D;
        boolean Hit;

        g2D = (Graphics2D) g;

        Hit = Shape1.intersectsLine(Shape2);
        g2D.drawString("intersects = " + Hit, 20, 145);

        g2D.draw(Shape1);
        g2D.draw(Shape2);
        g2D.draw(Shape3);

    }

}


Matrizes...para que afinal?

Matrizes durante o ensino básico pode parecer inútil além de resolver sistemas lineares. Acontece que sistemas lineares são extremamente úteis para resolver problemas de otimização em sistemas industriais resolvidos por Engenheiros de Produção. Mas Matrizes são a base para muitas aplicações na computação. Um delas que agora cito é a reflexão de uma imagem no seu eixo x ou y. Encontrei um código perfeito (cortesia de Byron Kiourtzoglou) exemplificando um método empregado em java para refletir tanto em x quanto em y, contudo, esse código só está fazendo reflexão em x. Para testar o código, basta usar basta montar o projeto com uma IDE como netbeans ou eclipse e por a imagem de teste no diretório "c:/" com nome de "image.png"

 


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package raizgeom;

/**
 *
 * @author Byron Kiourtzoglou
 */
import java.awt.Component;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;

public class BufferedImageFlipps {

    static BufferedImage image;
    static boolean imageLoaded = false;

    public static void main(String[] args) {

  // The ImageObserver implementation to observe loading of the image

  ImageObserver myImageObserver = new ImageObserver() {

    public boolean imageUpdate(Image image, int flags, int x, int y, int width, int height) {

if ((flags & ALLBITS) != 0) {

  imageLoaded = true;

  System.out.println("Image loading finished!");

  return false;

}

return true;

    }

  };

  // The image URL - change to where your image file is located!

  String imageURL = "c:/image.png";

  /**

   * This call returns immediately and pixels are loaded in the background

   * We use an ImageObserver to be notified when the loading of the image

   * is complete

   */

  Image sourceImage = Toolkit.getDefaultToolkit().getImage(imageURL);

  sourceImage.getWidth(myImageObserver);

  // We wait until the image is fully loaded

  while (!imageLoaded) {

try {

    Thread.sleep(100);

} catch (InterruptedException e) {

}

  }

  // Create a buffered image from the source image with a format that's compatible with the screen

  GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();

  GraphicsDevice graphicsDevice = graphicsEnvironment.getDefaultScreenDevice();

  GraphicsConfiguration graphicsConfiguration = graphicsDevice.getDefaultConfiguration();

  // If the source image has no alpha info use Transparency.OPAQUE instead

  image = graphicsConfiguration.createCompatibleImage(sourceImage.getWidth(null), sourceImage.getHeight(null), Transparency.BITMASK);

  // Copy image to buffered image

  Graphics graphics = image.createGraphics();

  // Paint the image onto the buffered image

  graphics.drawImage(sourceImage, 0, 0, null);

  graphics.dispose();

  // Flip the image vertically

  //AffineTransform tx = AffineTransform.getScaleInstance(1, -1);

 // tx.translate(0, -image.getHeight(null));

  //AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);

  //image = op.filter(image, null);

  // Flip the image horizontally

  AffineTransform tx = AffineTransform.getScaleInstance(-1, 1);

  tx.translate(-image.getWidth(null), 0);

  AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);

  image = op.filter(image, null);

  /* Flip the image vertically and horizontally; equivalent to rotating the image 180 degrees

  tx = AffineTransform.getScaleInstance(-1, -1);

  tx.translate(-image.getWidth(null), -image.getHeight(null));

  op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);

  image = op.filter(image, null); */

  // Create frame with specific title

  Frame frame = new Frame("Example Frame");

  // Add a component with a custom paint method

  frame.add(new CustomPaintComponent());

  // Display the frame

  int frameWidth = 300;

  int frameHeight = 300;

  frame.setSize(frameWidth, frameHeight);

  frame.setVisible(true);

    }

    /**
     * To draw on the screen, it is first necessary to subclass a Component and
     * override its paint() method. The paint() method is automatically called
     * by the windowing system whenever component's area needs to be repainted.
     */
    static class CustomPaintComponent extends Component {

  public void paint(Graphics g) {

// Retrieve the graphics context; this object is used to paint

// shapes

Graphics2D g2d = (Graphics2D) g;

/**

 * Draw an Image object The coordinate system of a graphics context

 * is such that the origin is at the northwest corner and x-axis

 * increases toward the right while the y-axis increases toward the

 * bottom.

 */

int x = 0;

int y = 0;

g2d.drawImage(image, x, y, this);

  }

    }

}


 

Canal Youtube sobre ensino básico + sobre aprenda a programar.

Segue o link do canal http://www.youtube.com/educacao que conta com centenas de videos ensinando tudo sobre matemática, física, química, português e biologia nos níveis de ensino fundamental e médio. Acredito fortemente que todo jovem deveria aprender a programar, por isso, indico também a Code Academy http://code.org/learn/codecademy e a Khan Academy http://code.org/khan-academy em http://code.org/ .

Fan Page Facebook

Para quem curtiu o blog, agora temos também nossa fan page no facebook.
https://www.facebook.com/edu.onc?ref=hl

Quer aprender a programar?

Quer aprender a programar? Sugiro que comece com java, mas ao mesmo tempo estude lógica de programação. Não precisa ficar somente nisso, pode ser divertido fazer jogos bem simples em alto nível com um engine de jogos 2D sem saber programar nada. Acredito que assim acaba-se instigando ainda mais a curiosidade e vontade de aprender mais baixo nível, de descobrir como fizeram os programadores. O site https://www.scirra.com/ contém o link para o download do Construct2 bem como dezenas de links com tutoriais e comentários da comunidade. Imagine lançar um jogo campeão de downloads para smartphones, tablets e/ou facebook? Link para o site do curso k-19 para download de apostilas grátis de programação: http://www.k19.com.br/downloads/apostilas Use ou eclipse http://www.eclipse.org/downloads/ ou netbeans http://www.oracle.com/technetwork/pt/java/javase/downloads/jdk-7-netbeans-download-432126.html para programar.

Teorema de Pitágoras sem fórmulas, você acredita em tudo que lhe dizem? Tire a prova! =) Parte 1

Esse é a primeira publicação que faço referente a educação. Apresento um código em java que realiza o cálculo da distância entre dois pontos, no caso, os pontos que formariam a hipotenusa de um triângulo retângulo isósceles de lados 1,1,hipotenusa(hip). Se fizéssemos esse procedimento com uma régua escolar teríamos um valor muito impreciso de 1,4 cm e nossos olhos perceberiam um pouco mais, para melhorarmos nossa precisão, podemos fazer um triângulo proporcionalmente maior. Se fizemos 10x, isto é, lados 10,10,10*hip teríamos a resposta de 10* maior, no entanto, nossa régua agora dá o valor de 14,1cm e mais uma vez nossos olhos nos deixam em dúvida. Se fizessemos 100x maior podemos supor que o valor seria 141,4cm. Tente fazer isso você mesmo. Existe uma afirmação que diz que se fizéssemos o cálculo perfeitamente preciso teríamos o valor da hipotenusa equivalente ao valor da raiz quadrada de 2(1,4142135623730950...), perceba que a ideia inicial que tive de medir com a régua estava nos dando valores cada vez mais precisos. Tive a ideia de fazer um programa em java que utilizasse de métodos para desenhar retas e pontos. Fiz o triângulo de lados 1,1,hipotenusa e o cálculo tem ótima precisa de 1.4142135623730951 com erro apenas no último dígito (1) que se compararmos com o cálculo feito por outros métodos mais precisos continuaria com ...0488016887242097... assim sendo o programa também tem suas limitações porém vamos assumir que para essa aproximação temos o valor de dois já que esse mesmo valor ao quadrado é aproximadamente 2,0000000000000001. Mas recentemente descobri que se montássemos um triângulo de lados 1, raiz quadrada de 2, hipotenusa, teríamos o valor impressionante da raiz quadrada de 3 como mostra a figura do link (http://www.geom.uiuc.edu/~demo5337/Group3/spiral.gif). Na figura, um dos lados de todos os outros triângulos não tem valor escrito, mas ele é igual a 1, ou seja, lados 1, 1, a para o primeiro tri. Para o segundo lados 1, a, b (note que a = raiz de 2 e b = raiz de 3) e por ai vai sucessivamente. O código abaixo irá mostrar meu algoritmo. Se desejar rodar o código basta copiá-lo para uma IDE de java (Netbeans ou Eclipse por ex.). Mas algumas saídas já adianto: Programei para nunca parar, pelo menos até aonde o programa não estourar memória. A primeira parte encerro por aqui, parte 2 incluirá a parte gráfica.
raiz de 1 1.0
raiz de 2 1.4142135623730951
raiz de 3 1.7320508075688774
raiz de 4 2.0
raiz de 5 2.23606797749979
raiz de 6 2.4494897427831783
raiz de 7 2.6457513110645907
raiz de 8 2.8284271247461903
raiz de 9 3.0000000000000004
raiz de 10 3.16227766016838
<?java


import java.awt.*;
import java.applet.*;
import java.awt.geom.*;

public class Line2D1 extends Applet {

    private Line2D Shape1;
    private Line2D Shape2;
    private Line2D Shape3;
    private Line2D iShape;
    //double diagonal;
    private Point2D Point1;
    private Point2D iPoint;
    double raizquadrada;
    boolean continua = true;

    public static void main(String[] args) {
        Line2D1 mede = new Line2D1();
        mede.raiziterativa();
        
    }

    public void raiziterativa() {

        boolean continua = true;

        while (continua == true) {
            iPoint = new Point2D.Double(0, raizquadrada);
            raizquadrada = iPoint.distance(Shape1.getP2());
            iShape = new Line2D.Double(Shape1.getP1(), iPoint);
            long i;
            i = Math.round(Math.pow(raizquadrada, 2)) ;

            System.out.println("raiz de " + i + " " + raizquadrada);
        }

    }

    public Line2D1() {
        Shape1 = new Line2D.Double(0, 0, 1, 0); // linha vertical vetor da esqPdir
        //Shape2 = new Line2D.Double();
        //Shape2.setLine(0.F, 0.F, 0.F, 1.F); // linha horizontal vetor de cimaPbaixo cpb
        //Shape3 = new Line2D.Double(120, 0, 20, 100); // diagonal cpb dpe.
        Point1 = new Point2D.Double(0, 1);
        Shape2 = new Line2D.Double(Shape1.getP1(), Point1);
        Shape3 = new Line2D.Double(Shape1.getP2(), Point1);

    }

    @Override
    public void paint(Graphics g) {
        Graphics2D g2D;
        boolean Hit;

        g2D = (Graphics2D) g;

        Hit = Shape1.intersectsLine(Shape2);
        g2D.drawString("intersects = " + Hit, 20, 145);

        g2D.draw(Shape1);
        g2D.draw(Shape2);
        g2D.draw(Shape3);

    }

}


Code Sniffer gratuito para blogspot

Para adicionar o code sniffer gratuitamente no seu blogspot, basta ir no menu editar html do seu blogspot e colar o seguinte código antes da tag "/head". Pronto, basta publicar seu código em modo html entre as tags:
<?java

<?java

//all code here

Créditos: "Thanks so much Alex Gorbatchev" Source: http://alexgorbatchev.com/SyntaxHighlighter/" http://alexgorbatchev.com/SyntaxHighlighter/manual/brushes/ para ver os formatos dos codigos de linguagens suportados. Copie e cole somente as que você realmente usa para não pesar no carregamento da página.
<link href="http://alexgorbatchev.com/pub/sh/current/styles/shCore.css" rel="stylesheet" type="text/css" />

<link href="http://alexgorbatchev.com/pub/sh/current/styles/shThemeEmacs.css" rel="stylesheet" type="text/css" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushAS3.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushBash.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushColdFusion.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushDelphi.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushDiff.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushErlang.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushGroovy.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJavaFX.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPerl.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPhp.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPlain.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPowerShell.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushRuby.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushScala.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js" type="text/javascript" />

<script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js" type="text/javascript" />

  

<script language="javascript" type="text/javascript">

 SyntaxHighlighter.config.bloggerMode = true;

 SyntaxHighlighter.all();

</script>




sábado, 23 de novembro de 2013