Список чтения для научного [закрытого] программиста

Вот код, который мы используем для Lilina:

<?php
/**
 * Handler for persistent data files
 *
 * @author Ryan McCue <cubegames@gmail.com>
 * @package Lilina
 * @version 1.0
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */

/**
 * Handler for persistent data files
 *
 * @package Lilina
 */
class DataHandler {
    /**
     * Directory to store data.
     *
     * @since 1.0
     *
     * @var string
     */
    protected $directory;

    /**
     * Constructor, duh.
     *
     * @since 1.0
     * @uses $directory Holds the data directory, which the constructor sets.
     *
     * @param string $directory 
     */
    public function __construct($directory = null) {
        if ($directory === null)
            $directory = get_data_dir();

        if (substr($directory, -1) != '/')
            $directory .= '/';

        $this->directory = (string) $directory;
    }

    /**
     * Prepares filename and content for saving
     *
     * @since 1.0
     * @uses $directory
     * @uses put()
     *
     * @param string $filename Filename to save to
     * @param string $content Content to save to cache
     */
    public function save($filename, $content) {
        $file = $this->directory . $filename;

        if(!$this->put($file, $content)) {
            trigger_error(get_class($this) . " error: Couldn't write to $file", E_USER_WARNING);
            return false;
        }

        return true;
    }

    /**
     * Saves data to file
     *
     * @since 1.0
     * @uses $directory
     *
     * @param string $file Filename to save to
     * @param string $data Data to save into $file
     */
    protected function put($file, $data, $mode = false) {
        if(file_exists($file) && file_get_contents($file) === $data) {
            touch($file);
            return true;
        }

        if(!$fp = @fopen($file, 'wb')) {
            return false;
        }

        fwrite($fp, $data);
        fclose($fp);

        $this->chmod($file, $mode);
        return true;

    }

    /**
     * Change the file permissions
     *
     * @since 1.0
     *
     * @param string $file Absolute path to file
     * @param integer $mode Octal mode
     */
    protected function chmod($file, $mode = false){
        if(!$mode)
            $mode = 0644;
        return @chmod($file, $mode);
    }

    /**
     * Returns the content of the cached file if it is still valid
     *
     * @since 1.0
     * @uses $directory
     * @uses check() Check if cache file is still valid
     *
     * @param string $id Unique ID for content type, used to distinguish between different caches
     * @return null|string Content of the cached file if valid, otherwise null
     */
    public function load($filename) {
        return $this->get($this->directory . $filename);
    }

    /**
     * Returns the content of the file
     *
     * @since 1.0
     * @uses $directory
     * @uses check() Check if file is valid
     *
     * @param string $id Filename to load data from
     * @return bool|string Content of the file if valid, otherwise null
     */
    protected function get($filename) {
        if(!$this->check($filename))
            return null;

        return file_get_contents($filename);
    }

    /**
     * Check a file for validity
     *
     * Basically just a fancy alias for file_exists(), made primarily to be
     * overriden.
     *
     * @since 1.0
     * @uses $directory
     *
     * @param string $id Unique ID for content type, used to distinguish between different caches
     * @return bool False if the cache doesn't exist or is invalid, otherwise true
     */
    protected function check($filename){
        return file_exists($filename);
    }

    /**
     * Delete a file
     *
     * @param string $filename Unique ID
     */
    public function delete($filename) {
        return unlink($this->directory . $filename);
    }
}

?>

Это хранит каждую запись как отдельный файл, который мы нашли, достаточно эффективно для использования (никакие ненужные данные не загружаются, и это быстрее для сохранения).

45
задан Grant Thomas 19 January 2013 в 19:55
поделиться

15 ответов

На каком-то этапе вам понадобится арифметика с плавающей запятой. Трудно сделать это хорошо, менее сложно сделать это грамотно, а легко сделать плохо. Этот документ необходимо прочитать:

Что должен знать каждый компьютерный ученый об арифметике с плавающей запятой

36
ответ дан 26 November 2019 в 20:59
поделиться

For generic C++ in scientific enviroments, Modern C++ Design by Andrei Alexandrescu is probably the standard book about the common design patterns.

3
ответ дан 26 November 2019 в 20:59
поделиться

this might be useful: the nature of mathematical modeling

0
ответ дан 26 November 2019 в 20:59
поделиться

I would suggest any of the numerical recipes books (pick a language) to be useful.

Depending on the languages you use or if you will be doing visualization there can be other suggestions.

Another book I really like is Object-Oriented Implementation of Numerical Methods, by Didier Besset. He shows how to do many equations in Java and smalltalk, but what is more important is that he does a fantastic job with helping to show how to optimize equations for use on a computer and how to deal with errors because of limitations on the computer.

6
ответ дан 26 November 2019 в 20:59
поделиться

In terms of languages, I think you have a good coverage. Python is great for experimentation and prototyping, Mathematica is good for helping with the theoretical stuff, and C/C++ are there if you need to do serious number crunching.

I might also suggest you develop an appreciation of an assembly language and also a functional language (such as Haskell), not really to use, but rather because of the effect they have on your programming skills and style, and of the concepts they bring home to you. They might also come in handy one day.

I would also consider it vital to learn about parallel programming (concurrent/distributed) as this is the only way to access the sort of computing power that sometimes is necessary for scientific problems. Exposure to functional programming would be quite helpful in this regard, whether or not you actually use a functional language to solve the problem.

Unfortunately I don't have much to suggest in the way of reading, but you may find The Scientist and Engineer's Guide to Digital Signal Processing helpful.

10
ответ дан 26 November 2019 в 20:59
поделиться

My first suggestion is that you look at the top 5 universities for your specific field, look at what they're teaching and what the professors are using for research. That's how you can discover the relevant language/approach.

Also have a look at this stackoverflow question ("practices-for-programming-in-a-scientific-environment").

You're doing statistical/finance modeling? I use R in that field myself, and it is quickly becoming the standard for statistical analysis, especially in the social sciences, but in finance as well (see, for instance, http://rinfinance.com). Matlab is probably still more widely used in industry, but I have the sense that this may be changing. I would only fall back to C++ as a last resort if performance is a major factor.

Look at these related questions for help finding reading materials related to R:

In terms of book recommendations related to statistics and finance, I still think that the best general option is David Ruppert's "Statistics and Finance" (you can find most of the R code here and the author's website has matlab code).

Lastly, if your scientific computing isn't statistical, then I actually think that Mathematica is the best tool. It seems to get very little mention amongst programmers, but it is the best tool for pure scientific research in my view. It has much better support for things like integration and partial differential equations that matlab. They have a nice list of books on the wolfram website.

12
ответ дан 26 November 2019 в 20:59
поделиться

Я настоятельно рекомендую

Научный и инженерный C ++: Введение с передовыми методами и примерами Бартона и Накмана

Не пугайтесь его возраста, он отличный. Числовые рецепты на вашем любимом языке (если это C, C ++ или Fortran) являются всеобъемлющими и отлично подходят для изучения не всегда лучших алгоритмов для каждой задачи.

Мне также нравятся

Параллельные научные вычисления в C ++ и MPI: цельный подход к параллельным алгоритмам и их реализации Карниадакис

. Чем раньше вы начнете параллельные вычисления, тем лучше.

25
ответ дан 26 November 2019 в 20:59
поделиться

MATLAB широко используется в проектировании для проектирования, быстрой разработки и даже производственных приложений (в моем текущем проекте есть DLL, созданная с помощью MATLAB, для выполнения некоторого расширенного анализа чисел, что было проще, чем в нашем родной C ++, и наши FPGA также используют ядра, сгенерированные MATLAB, для обработки сигналов, что намного проще, чем кодировать то же самое вручную на VHDL). Также существует набор финансовых инструментов для MATLAB , который может вас заинтересовать.

Это не означает, что MATLAB - лучший выбор для вашей области, но, по крайней мере, в инженерии он широко используется, а не скоро куда-нибудь уеду.

4
ответ дан 26 November 2019 в 20:59
поделиться

После того, как вы начнете работать, я настоятельно рекомендую прочитать этот блог .

Он описывает, как вы используете шаблоны C ++ для обеспечения типобезопасных единиц. Так, например, если вы умножите скорость на время, вы получите расстояние и т. Д.

2
ответ дан 26 November 2019 в 20:59
поделиться

Книга Дональда Кнута о получисленных алгоритмах.

4
ответ дан 26 November 2019 в 20:59
поделиться
0
ответ дан 26 November 2019 в 20:59
поделиться

Одна из проблем, с которой сталкиваются научные программисты, - это поддержка хранилища кода (и данных), которое другие могут использовать для воспроизведения ваших экспериментов. По моему опыту, этот навык не требуется при коммерческой разработке.

Вот некоторые прочтения по этому поводу:

Они находятся в контексте вычислительной биологии, но я предполагаю, что это применимо к большинству научного программирования.

Также посмотрите Python Scripting for Computational Science .

4
ответ дан 26 November 2019 в 20:59
поделиться

Я научный программист, который только начал работать в этой области за последние 2 года. Я больше увлекаюсь биологическим и физическим моделированием, но держу пари, что то, что вы ищете, очень похоже. Пока я подал заявление о приеме на работу и стажировке, я не думал, что было так важно знать две вещи, но из-за них я в конечном итоге упустил возможности. Одним из них был MATLAB, о котором уже упоминалось. Другой был дизайн базы данных - независимо от того, в какой области SP вы работаете, вероятно, будет много данных, которыми нужно как-то управлять.

Книга Майкла Эрнандеса Дизайн баз данных для простых смертных была рекомендована мне как хорошее начало и очень помогла мне в подготовке. Я также хотел бы убедиться, что вы понимаете хотя бы некоторые базовые SQL , если вы не понимаете

7
ответ дан 26 November 2019 в 20:59
поделиться

Чтение исходного кода тоже очень помогает. Python великолепен в этом смысле. Я узнал огромное количество информации, просто покопавшись в исходных кодах научных инструментов Python. Вдобавок к этому, просмотр списков рассылки и форумов ваших любимых инструментов может еще больше повысить ваши навыки

.
2
ответ дан 26 November 2019 в 20:59
поделиться

Написание научного программного обеспечения: Руководство по хорошему стилю - хорошая книга с общими советами по современному научному программированию.

0
ответ дан 26 November 2019 в 20:59
поделиться